Compare commits

...
30 Commits
Author SHA1 Message Date
sam 6c42f64bfa chore(release): v1.60.0
Quality / check (push) Canceled after 18s
deploy / gate (push) Successful in 4m39s
deploy / archied-image (push) Successful in 2m52s
deploy / agent-image (push) Successful in 3m21s
deploy / dist-zip (push) Successful in 1m47s
2026-11-03 09:51:30 +11:00
sam d74216c6b7 docs(changelog): curator issue tools (#1770)
Quality / check (push) Successful in 4m3s
deploy / gate (push) Successful in 4m42s
deploy / archied-image (push) Successful in 2m49s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
2026-11-03 09:43:45 +11:00
sam 0b7ce448ab fix(e2e): checks follow the sidebar navigation; trim stray button and caption whitespace (#1789)
Quality / check (push) Successful in 3m52s
deploy / gate (push) Successful in 4m36s
deploy / archied-image (push) Successful in 3m16s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
2026-11-03 09:35:19 +11:00
sam 2fb8c09a00 refactor(webui): extract the workflows module (#1778)
Quality / check (push) Successful in 4m23s
deploy / gate (push) Successful in 4m37s
deploy / archied-image (push) Successful in 2m51s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
2026-11-03 08:39:40 +11:00
sam 0442f1849f refactor(webui): extract the audit module and its export guards (#1778)
Quality / check (push) Canceled after 1m17s
deploy / gate (push) Successful in 4m33s
deploy / archied-image (push) Successful in 2m52s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
2026-11-03 08:38:22 +11:00
sam cf049797b0 refactor(webui): extract the schedules and alerts modules (#1778)
Quality / check (push) Canceled after 1m5s
deploy / gate (push) Successful in 4m33s
deploy / archied-image (push) Successful in 2m48s
deploy / agent-image (push) Successful in 12s
deploy / dist-zip (push) Skipped
2026-11-03 08:37:15 +11:00
sam 18e6fe6af6 refactor(webui): extract the chat module and its ask/file state (#1778)
Quality / check (push) Canceled after 1m5s
deploy / gate (push) Successful in 4m35s
deploy / archied-image (push) Successful in 2m48s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
2026-11-03 08:36:09 +11:00
sam e8a84d3e41 refactor(webui): extract the control-plane and logs modules (#1778)
Quality / check (push) Canceled after 1m17s
deploy / gate (push) Successful in 4m31s
deploy / archied-image (push) Successful in 2m49s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
2026-11-03 08:34:51 +11:00
sam c5f4541cbf refactor(webui): extract the access policies and denials module (#1778)
Quality / check (push) Canceled after 1m5s
deploy / gate (push) Successful in 4m35s
deploy / archied-image (push) Successful in 2m49s
deploy / agent-image (push) Successful in 12s
deploy / dist-zip (push) Skipped
2026-11-03 08:33:46 +11:00
sam 369e5038ca refactor(webui): extract the identities and tokens module (#1778)
Quality / check (push) Canceled after 1m9s
deploy / gate (push) Successful in 4m34s
deploy / archied-image (push) Successful in 2m52s
deploy / agent-image (push) Successful in 10s
deploy / dist-zip (push) Skipped
2026-11-03 08:32:44 +11:00
sam 66862a1bab refactor(webui): extract the orgs resource module (#1778)
Quality / check (push) Successful in 4m2s
deploy / gate (push) Successful in 4m39s
deploy / archied-image (push) Successful in 2m51s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
2026-11-03 08:28:36 +11:00
sam 25dcdb2d19 refactor(webui): extract the extensions resource module (#1778)
Quality / check (push) Successful in 5m1s
deploy / gate (push) Successful in 4m35s
deploy / archied-image (push) Successful in 2m46s
deploy / agent-image (push) Successful in 10s
deploy / dist-zip (push) Skipped
2026-11-03 08:22:02 +11:00
sam 1830a89898 refactor(webui): extract the harness resource module (#1778)
Quality / check (push) Successful in 3m56s
deploy / gate (push) Successful in 4m34s
deploy / archied-image (push) Successful in 2m55s
deploy / agent-image (push) Successful in 12s
deploy / dist-zip (push) Skipped
2026-11-03 08:17:12 +11:00
sam 6e718e165a feat(curator): issue_list and issue_create tools via the daemon (#1770)
Quality / check (push) Successful in 4m6s
deploy / gate (push) Successful in 4m30s
deploy / archied-image (push) Successful in 2m50s
deploy / agent-image (push) Successful in 12s
deploy / dist-zip (push) Skipped
2026-11-03 08:12:05 +11:00
sam 0a37b551f5 refactor(webui): extract the tasks resource module (#1778)
Quality / check (push) Successful in 3m47s
deploy / gate (push) Successful in 4m32s
deploy / archied-image (push) Successful in 2m51s
deploy / agent-image (push) Successful in 10s
deploy / dist-zip (push) Skipped
2026-11-03 08:06:56 +11:00
sam 864b87faa6 refactor(webui): extract event-types, mappings and sources modules (#1778)
Quality / check (push) Successful in 3m52s
deploy / gate (push) Successful in 4m29s
deploy / archied-image (push) Successful in 2m48s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
Same pattern as the bindings pilot: eventTypesAPI (registers unconditionally,
list answers enabled:false without a store), mappingsAPI and sourcesAPI
(constructed only when their store is configured, 503 stub otherwise).
Shared helpers unsignedSources/recentRefusals/listedIn stay on Server; the
dispatch-ledger handler stays shared for captures/tasks. task check green.
2026-11-03 07:42:50 +11:00
sam d55d8580cf refactor(webui): extract the bindings resource module (#1778)
Pilot for one-module-per-resource: bindingsAPI owns the /api/bindings*
routes and their handlers, constructed only when the binding store is
configured; a 503 stub mounts the same routes otherwise, preserving the
old not-configured answers. Handlers move off *Server unchanged in
behavior; the shared dispatch-ledger handler stays on Server for the
captures/tasks routes. task check green.
2026-11-03 07:01:12 +11:00
sam 63229d1711 refactor(storecontract): assert every store interface at its implementation (#1781)
Complete the var _ storecontract.X = (*T)(nil) sweep so each of the 31
contract interfaces is compiler-checked against at least one adapter:
postgres.Store (19), postgres.EDA (11, consolidated into edastore.go),
staterpc.Client (29). Removes the scattered single-line assertions from
harness_secrets.go, edastore_eventtypes.go, sources.go, run_credentials.go.
task check green.
2026-11-03 06:24:09 +11:00
sam 56044476fc chore(release): v1.59.0
Quality / check (push) Successful in 3m53s
deploy / gate (push) Successful in 4m21s
deploy / archied-image (push) Successful in 2m45s
deploy / agent-image (push) Successful in 3m15s
deploy / dist-zip (push) Successful in 2m35s
2026-11-03 06:15:09 +11:00
sam 796bfd0045 docs(changelog): forge extensions gain CreateIssue
Quality / check (push) Successful in 7m12s
deploy / gate (push) Successful in 5m16s
deploy / archied-image (push) Successful in 3m2s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
2026-11-03 02:43:25 +11:00
sam abcb72a76a feat(curator): dry-run self-intake pass with run inspection tools (#1770)
Curators could only reach the workflow/integration tools; there was no way
to survey task runs. Adds run_list/run_events to the shared registry
(guarded as read on task kind), attaches the instance's acting principal
to curator model calls so guarded tools authorize, and records a pass's
final text as a pass.summary action so the report is inspectable. Ships a
dry-run self-intake definition in dev.toml/config.example.toml declaring
only those two tools, so it cannot file issues yet.
2026-11-03 02:35:06 +11:00
sam 443a7a501b refactor(storecontract): split the store contract into topical files (#1781)
Pure move: one 624-line storecontract.go becomes storecontract.go
(package doc + composed TaskStore), task.go, capture.go, binding.go,
mapping.go, source.go, status.go, resource.go, credentials.go and
errors.go. The package remains the single seam; no declaration changed
(verified line-identical against HEAD). task check green.
2026-11-03 02:27:57 +11:00
sam 88e86776e8 feat(forge): add CreateIssue to the forge contract (#1770)
Quality / check (push) Successful in 4m10s
deploy / gate (push) Successful in 4m43s
deploy / archied-image (push) Successful in 2m54s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
Issue-level writes could comment and close but not open an issue, so no
curator or workflow stage can file its own work yet. Adds the rpc to
proto/forge/v1, regenerates the contracts, and threads it through the
domain interface, forgerpc client/server (comment permission, like
CloseIssue), forgeext, and the archipelago SDK + gitea/github plugins.
2026-11-03 02:04:56 +11:00
sam e10bb161fe docs(prds): mark the self-development ADR as decided, not built (#1769) 2026-11-03 01:52:06 +11:00
sam 3b525b7482 docs(prds): mark the self-development ADR as record, not mechanism (#1769) 2026-11-03 01:50:54 +11:00
sam c2cc10ebfa docs(prds): record the self-development loop decision (#1769) 2026-11-03 01:36:31 +11:00
sam 2f8076d7f8 fix(access): forbid clause scopes the canary grant against its developer role (#1727)
Quality / check (push) Successful in 3m37s
deploy / gate (push) Successful in 4m45s
deploy / archied-image (push) Successful in 2m53s
deploy / agent-image (push) Successful in 10s
deploy / dist-zip (push) Skipped
Service accounts created through the identities API are assigned the
developer role in the request's org, whose shipped policy permits read and
write across the org -- the permit alone did not scope the canary. Install a
matching org-canary-grant-forbid policy (access.CanaryGrantForbidPolicy) that
negates exactly the permit's surface for the canary identity; a forbid wins
within the level, so the role can no longer widen access. Engine tests pin
the surface with the principal carrying the developer role, and the
rehearsal now proves it live: the scoped token gets 403 on /api/access/policies
and 200 on /api/chat/update, and the full canary loop runs on it.

task check passes; task canary:rehearse green (REHEARSE_EXIT=0).
2026-11-02 06:23:38 +11:00
sam c180a2debb feat(access): scoped canary grant replaces instance-admin CANARY_TOKEN (#1727)
Quality / check (push) Successful in 3m49s
deploy / gate (push) Successful in 4m48s
deploy / archied-image (push) Successful in 2m55s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
The canary now authenticates as a dedicated service-account identity in the
system org whose only grant is access.CalaryGrantPolicy: read the signal
endpoints (chat update, alerts, logs, tasks), read and write the
update-settings resource, and trigger an update install. CANARY_TOKEN no
longer carries instance admin; DEPLOY_TOKEN stays CI-only.

- authorize: POST /api/chat/update/install and /defer map to
  update on Object::"update" (dashboard) instead of run on any workflow,
  so the grant can cover installs without granting workflow runs
- accounts: active service-account identities may authenticate with bearer
  tokens (CanAct), not just users
- new POST /api/identities/{id}/tokens (behind manage_identities) mints a
  token for a named non-user identity; new AccountService RPC
  BindIdentityPersonalToken backs it remotely, refusing user-kind targets,
  with the caller recorded as audit actor
- engine tests pin the grant's exact allow/deny surface

RELEASING.md documents the one-time setup. task check passes on this tree.
2026-11-02 06:03:41 +11:00
sam 5356745968 fix(releaseupdate): address review findings on the #1725 canary change
Quality / check (push) Successful in 3m39s
deploy / gate (push) Successful in 4m28s
deploy / archied-image (push) Successful in 3m11s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
- one shared UpdateStateDir() resolver for daemon and dashboard, instead of
  two copies that could drift
- the recovery path for a committed/rolled-back journal writes
  installed.json too, so a crash after the outcome phase cannot lose the
  install record
- JudgeCanaryNow is the explicit signals-only entry point for promoting
  without the window, replacing the zero-install-time sentinel
- canary version comparisons use IssuedAt, matching Promote's replay rule,
  so semver/issued-at divergence cannot wedge check red; queuedBehind
  reuses the judgeable predicate instead of a looser check
- promote prints the channel/pin; promote.yml cancels superseded runs
- canary card: no duplicated elapsed rendering, channel row waits for the
  settings resource instead of showing a default, agent fallback '?'
- rehearsal script bounds its docker build/push/run calls

task check passes on this tree.
2026-11-02 02:45:26 +11:00
sam 5b5059615b feat(releaseupdate): judge the installed release, window from install (#1725)
Quality / check (push) Successful in 4m2s
deploy / gate (push) Successful in 4m31s
deploy / archied-image (push) Successful in 3m14s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
The canary window now counts from when a release is installed on the host
(installed.json / installed_at in the update snapshot), not from the
statement's issued_at, and 'release canary check' judges the release the
canary actually runs via its exact-pin tag instead of the moving next tag.
A newer release on next queues behind the one being judged instead of
restarting the clock, so stable moves once per release.

New subcommands: canary status (read-only state, signals, verdict), canary
promote (promote now when hard checks pass), canary unpin (back to next),
and start -force. A held/pinned canary is verified installable every check
and a stranded pin fails the run red instead of looking green. Rollback
pre-flight checks stable's zip and agent image digests before pinning.
Relative signals are judged whenever both windows carry minimum data, so a
breach rolls back mid-window; promote still needs the full window unless
the operator promotes early (new promote.yml workflow_dispatch). The window
is configurable via -window / CANARY_WINDOW.

Also: dashboard canary status card (ui), and task canary:rehearse, a local
end-to-end rehearsal of publish -> canary start -> status -> check ->
promote against a throwaway registry and host.

task check passes; rehearsal run green (REHEARSE_EXIT=0).
2026-11-02 01:15:29 +11:00
118 changed files with 6231 additions and 2641 deletions

No files matched your search

+12 -4
View File
@@ -1,7 +1,9 @@
# Every 15 minutes, checks how the newest release on the `next` channel is
# running on the canary host. If a hard check fails, the canary goes back to
# the stable release straight away. If the release stays healthy for 24 hours,
# it's promoted to stable. A rollback fails the run, so it shows up red.
# Every 15 minutes, checks how the release installed on the canary host is
# running, judged over the window counted from its install (-window, default
# 24h; CANARY_WINDOW overrides it). If a hard check fails, the canary goes
# back to the stable release straight away. If the release stays healthy for
# the window, it's promoted to stable. A rollback fails the run, so it shows
# up red.
name: canary
on:
@@ -48,6 +50,12 @@ jobs:
- name: Judge the canary
env:
ARCHIE_CANARY_TOKEN: ${{ secrets.CANARY_TOKEN }}
CANARY_WINDOW: ${{ vars.CANARY_WINDOW }}
run: |
window_args=()
if [ -n "$CANARY_WINDOW" ]; then
window_args=(-window "$CANARY_WINDOW")
fi
"$RUNNER_TEMP/archied" release canary check -dashboard "${{ vars.CANARY_URL }}" \
"${window_args[@]}" \
-latest git.catlow.cloud/sam/archied,git.catlow.cloud/sam/archie-agent
+6 -2
View File
@@ -418,8 +418,12 @@ jobs:
"$api/repos/$repo/releases" >/dev/null
echo "published release notes for $tag"
# The canary host follows the `next` channel. canary.yml then decides
# whether this release is promoted to stable or the canary is rolled back.
# The canary host follows the `next` channel. canary.yml then judges the
# release installed on the canary and decides whether it is promoted to
# stable or the canary is rolled back. The start is queue-safe: a release
# published while the canary still judges a newer one is queued behind
# it and picked up by the next check, so the running window isn't
# restarted under a different release.
- name: Install the release on the canary
if: vars.CANARY_URL != ''
env:
+55
View File
@@ -0,0 +1,55 @@
# Promotes the release the canary is running right now, without waiting out
# the judging window: the canary's signals must show no hard failure and no
# relative breach, otherwise the run refuses and fails. Dispatch it with the
# version the canary runs (`archied release canary status` shows it).
name: promote
on:
workflow_dispatch:
inputs:
version:
description: "release the canary is expected to run; must match what it runs"
required: true
type: string
concurrency:
group: promote
cancel-in-progress: true
permissions:
contents: read
packages: write
jobs:
promote:
if: vars.CANARY_URL != ''
runs-on: self-hosted
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: main
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
# The self-hosted runner keeps the Go caches on disk between jobs, and
# archiving them for the Actions cache takes minutes.
cache: false
- name: Build archied
# The promote never serves the dashboard, so the build leaves it out.
run: go build -tags no_ui -o "$RUNNER_TEMP/archied" ./cmd/archied
# Promotion retags stable and the images' latest in the registry.
- name: Log in to the Gitea registry
run: echo "${{ secrets.DEPLOY_TOKEN }}" | docker login git.catlow.cloud -u "${{ github.actor }}" --password-stdin
- name: Promote the canary's release
env:
ARCHIE_CANARY_TOKEN: ${{ secrets.CANARY_TOKEN }}
run: |
"$RUNNER_TEMP/archied" release canary promote -dashboard "${{ vars.CANARY_URL }}" \
-version "${{ inputs.version }}" \
-latest git.catlow.cloud/sam/archied,git.catlow.cloud/sam/archie-agent
+12
View File
@@ -5,6 +5,18 @@ release's per-component sections are labelled beneath its heading.
## [Unreleased]
## [1.60.0] - 2026-11-02
### archied
- Curators can list a repository's open issues and file new ones with the `issue_list` and `issue_create` tools, which reach the forge through the daemon. A curator files only when its definition declares `issue_create`; the shipped self-intake example runs in dry run with `issue_list` for deduplication. Listing every open issue needs the forge extensions from the archipelago release after 1.2.0.
## [1.59.0] - 2026-11-02
### archied
- Forge extensions can open issues: the forge surface gains `CreateIssue` alongside list, comment and close, and the bundled Gitea and GitHub extensions implement it.
## [1.58.1] - 2026-11-01
### archied
+122 -20
View File
@@ -78,27 +78,64 @@ release rather than committing the fix on top of a tagged one.
The canary is the production host, following `next`. Every quarter hour
`canary.yml` runs `archied release canary check`, which reads the canary
through its dashboard API and judges the release on `next`:
through its dashboard API and judges **the release the canary actually runs**,
not the moving `next` tag:
| Signal | Source | Fails when |
| --- | --- | --- |
| Install outcome | `GET /api/chat/update` | the canary doesn't run the release (the watchdog rolled it back) |
| Install outcome | `GET /api/chat/update` | the canary doesn't run the judged release (the watchdog rolled it back) |
| Readiness | `GET /health/detailed` | the rollup isn't `ok` |
| Alerts | `GET /api/alerts` | an open `action` alert was first raised after the release was issued |
| Error log | `GET /api/logs?level=error` | error lines per day exceed `2 × baseline + 10` |
| Alerts | `GET /api/alerts` | an open `action` alert was first raised after the release was installed |
| Error log | `GET /api/logs?level=error` | error lines per window exceed `2 × baseline + 10` |
| Task outcomes | `GET /api/tasks` | the share of finished tasks that parked or died rose more than 10 points |
- **Control.** The canary's own 24 hours before the release was issued. With
- **Control.** The canary's own window before the release was installed. With
one production host there's no simultaneous control.
- **Window.** 24 hours from issue, one cycle of schedules and traffic. The
first 30 minutes are for the install and restart.
- **Window.** 24 hours counted from the **install** on the canary, not from
the release's issue time: the host records it in `installed.json`
(`committed_at`) and reports it as `installed_at` in `GET /api/chat/update`.
One cycle of schedules and traffic. The first 30 minutes are for the install
and restart. `canary.yml` passes `-window` when the `CANARY_WINDOW` Actions
variable is set; the flag defaults to 24h. A host that doesn't report an
install time degrades to the release statement's issue time.
- **Hard signals** (install, readiness, alerts) roll back at any check after
that. **Relative signals** (errors, tasks) are judged at the end of the
window.
that. **Relative signals** (errors, tasks) are judged against the baseline
whenever both windows carry enough data, so a breach rolls the release back
even mid-window; a full window with no failure promotes it.
- **Too little data skips a signal** rather than failing it: fewer than 5
finished tasks in the window, or an error log that reaches back less than an
hour into the baseline. A log read that stops short of a window is scaled to
a full day from what it covers.
a full window from what it covers.
### Queueing
`deploy.yml` installs each new release on the canary with
`archied release canary start -version V`, which first points the canary back
at `next` (clearing any rollback pin) and then installs `V` — unless the
canary is already judging a release newer than stable that isn't `V`, in which
case `V` is **queued** behind it and the canary keeps running what it judges.
`-force` installs regardless. A `check` that promotes (or finds nothing to
judge) installs the newer `next` in the same run, so a queue drains one
release per promotion.
### Subcommands
```
archied release canary status read-only: channel/pin, installed release and
installed_at, stable/next, window progress, and
the verdict the current signals would give
archied release canary start point the canary at next and install -version,
queued behind a release being judged (-force to
override)
archied release canary check judge the installed release over -window
(default 24h): promote, pick up a newer next,
or roll back; a held canary is reported, and a
held pin that is no longer installable fails
the run red
archied release canary promote promote the installed release now if its
signals pass; refuses with exit 1 otherwise
archied release canary unpin return the canary to next from any pin
```
### Promote
@@ -106,32 +143,97 @@ A release that passes the window is promoted: `stable` is retagged to the
`v<version>` manifest. The signature covers the statement, not the tag, so the
retag needs no signing key. The `archied` and `archie-agent` images' `:latest`
move to their `:v<version>` first, and the agent image must be the digest the
statement pins. Promotion refuses a prerelease and a release issued
before the one `stable` names, the same replay rule hosts enforce. The decision
and its reasons are in the `canary` run log.
statement pins. Promotion refuses a prerelease and a release issued before the
one `stable` names, the same replay rule hosts enforce. The decision and its
reasons are in the `canary` run log.
Early promotion is a dispatch away: the **promote** workflow
(`.github/workflows/promote.yml`) takes a `version` input and runs
`archied release canary promote -version V` on the canary. It judges the
release the canary runs — the window doesn't matter for the decision — and
refuses (red run) on any hard failure or relative breach with enough data.
### Roll back
`stable` stays put, and the run turns red. The canary is pinned to the `stable`
version through its update settings and reinstalled through its dashboard.
`stable` stays put, and the run turns red. Before the canary is pinned to
`stable`, `check` verifies `stable` is actually installable — its statement's
zip blob must still be in the release repository and its pinned agent image
must still resolve (`releaseupdate.Installable`). If it isn't, the run fails
loudly and the canary stays on `next` rather than being stranded on a pin.
Otherwise the canary is pinned to the `stable` version through its update
settings and reinstalled through its dashboard.
A release whose migrations differ from `stable`'s can't go back without
restoring the pre-update database snapshot, which loses every write since. The
canary is held on the failed release instead (pinned to it) and the fix goes
forward in the next release. The next release's deploy points the canary back at
`next`.
forward in the next release. The next release's deploy points the canary back
at `next`.
A pinned canary isn't judged, so a rollback is decided once.
A pinned canary isn't judged, so a rollback is decided once — but `check`
verifies the pin is still installable every run, so a stranded pin shows red
instead of green. `archied release canary unpin` returns the canary to `next`
by hand.
### Configuration
| Name | Kind | Holds |
| --- | --- | --- |
| `CANARY_URL` | Actions variable | the canary's dashboard URL; unset disables the canary steps |
| `CANARY_TOKEN` | Actions secret | a personal API token on the canary with instance admin |
| `DEPLOY_TOKEN` | Actions secret | registry and repository write, for publishing, promoting and the release push |
| `CANARY_TOKEN` | Actions secret | an API token bound to a dedicated `service_account` identity on the canary, carrying only the canary grant policy (see below) — never instance admin |
| `CANARY_WINDOW` | Actions variable | optional `-window` override for `canary check`; unset is 24h |
| `DEPLOY_TOKEN` | Actions secret | registry and repository write, for publishing, promoting and the release push; stays CI-only, promotion runs in CI and never on the host |
| `RELEASE_SIGNING_KEY` | Actions secret | the release signing seed |
#### Setting up `CANARY_TOKEN` once
`CANARY_TOKEN` is a bearer token for a dedicated service-account identity in
the system org whose only grant is the canary policy
(`access.CanaryGrantPolicy`): read the signal endpoints (`GET /api/chat/update`,
`GET /api/alerts`, `GET /api/logs`, `GET /api/tasks`), read and write the
`update-settings` resource, and trigger an update install
(`POST /api/chat/update/install`). It carries no other rights, and instance
admin is never needed. With an instance-admin token (for example the operator
session), run against the canary host:
```bash
# 1. Create the service-account identity in the system org.
curl -X POST "$CANARY_URL/api/identities" -H "Authorization: Bearer $ADMIN" \
-H 'Content-Type: application/json' \
-d '{"kind":"service_account","display_name":"ci-canary"}'
# -> {"id":"<canary-identity-id>", ...}
# 2. Issue its token (shown exactly once).
curl -X POST "$CANARY_URL/api/identities/<canary-identity-id>/tokens" \
-H "Authorization: Bearer $ADMIN" -H 'Content-Type: application/json' \
-d '{"name":"ci-canary","days":90}'
# -> {"id":"<token-hash>","token":"archie_pat_..."} -- store the token value as the CANARY_TOKEN secret
# 3. Install the grant pair, scoped to that identity. The policies' org is
# pinned to the caller's org (org-sys for the instance admin), so the
# bodies need no org field. The permit alone is not enough: service
# accounts created through the API are assigned the developer role, so a
# matching forbid (installed second) negates everything outside the
# permit's surface for that identity.
curl -X PUT "$CANARY_URL/api/access/policies" -H "Authorization: Bearer $ADMIN" \
-H 'Content-Type: application/json' \
-d '{"id":"org-canary-grant","level":"org","text":"permit(principal, action, resource) when {\n resource.org == principal.org &&\n principal == Archie::Identity::\"<canary-identity-id>\" &&\n (\n (action == Archie::Action::\"read\" && [\"dashboard\", \"task\"].contains(resource.kind)) ||\n (action == Archie::Action::\"read\" && resource == Archie::Object::\"update-settings\") ||\n (action == Archie::Action::\"update\" && resource == Archie::Object::\"update\") ||\n (action == Archie::Action::\"manage_identities\" && resource == Archie::Object::\"update-settings\")\n )\n};"}'
```
The second policy forbids the canary identity from everything the permit does
not name, so its developer role cannot widen the grant:
```bash
curl -X PUT "$CANARY_URL/api/access/policies" -H "Authorization: Bearer $ADMIN" \
-H 'Content-Type: application/json' \
-d '{"id":"org-canary-grant-forbid","level":"org","text":"forbid(principal, action, resource) when {\\n resource.org == principal.org &&\\n principal == Archie::Identity::\\\"<canary-identity-id>\\\" &&\\n !(\\n (action == Archie::Action::\\\"read\\\" && [\\\"dashboard\\\", \\\"task\\\"].contains(resource.kind)) ||\\n (action == Archie::Action::\\\"read\\\" && resource == Archie::Object::\\\"update-settings\\\") ||\\n (action == Archie::Action::\\\"update\\\" && resource == Archie::Object::\\\"update\\\") ||\\n (action == Archie::Action::\\\"manage_identities\\\" && resource == Archie::Object::\\\"update-settings\\\")\\n )\\n};"}'
```
The policy texts are exactly `access.CanaryGrantPolicy` and
`access.CanaryGrantForbidPolicy` from `internal/domain/access/canary.go` with
the identity id filled in. The canary needs no other rights: `GET
/health/detailed` is unauthenticated, and every other call it makes is covered
by the grant pair.
The runner must reach `CANARY_URL`. Without a canary a release stays on `next`
until promoted by hand, under the same refusals:
+7
View File
@@ -221,6 +221,13 @@ tasks:
cmds:
- node e2e/run.cjs {{.CLI_ARGS}}
canary:rehearse:
# Local rehearsal only: spins up its own registry, database and host, and
# is deliberately absent from check and CI.
desc: Rehearse the release-canary loop on a throwaway local host (needs docker; never part of the gate)
cmds:
- sh tools/canary-rehearse.sh
build:
desc: Build archie services and agent binaries
deps: [ui]
+17
View File
@@ -94,3 +94,20 @@ target = "127.0.0.1:9090"
# releases_key = "base64 public key"
# catalogue = "registry.example/owner/archipelago/catalogue"
# catalogue_key = "base64 public key"
# Long-running agent loops that maintain memory, skills and — in dry run —
# file follow-up issues from recent runs. Definitions are data: the server
# validates them and the gateway applies them live.
# [[curators]]
# name = "self-intake"
# interval = "1h"
# tools = ["run_list", "run_events", "issue_list"]
# instructions = """
# You are archie's self-intake curator, in dry run. Each pass: list recent
# task runs with run_list, inspect anything parked or failed with run_events,
# check issue_list for each repo so nothing already open is repeated, then
# report candidate follow-up issues, each tied to the run that produced it.
# Do not create issues.
# """
# To let it file: add "issue_create" to tools and tell it to file each
# candidate (citing the run) instead of only reporting it.
+11
View File
@@ -45,3 +45,14 @@ listen = "127.0.0.1:8585"
[services.daemon]
target = "127.0.0.1:8587"
listen = "127.0.0.1:8587"
# Dry-run self-intake curator (#1770): surveys recent runs and reports
# candidate follow-up issues as pass summaries; declares no issue-creating
# tool, so it cannot file. Needs a chat model configured to run at all.
[[curators]]
name = "self-intake"
interval = "1h"
tools = ["run_list", "run_events", "issue_list"]
instructions = """
You are archie's self-intake curator, in dry run. Each pass: list recent task runs with run_list, inspect anything parked or failed with run_events, check issue_list for each repo so nothing already open is repeated, then report candidate follow-up issues — concrete, each tied to the run that produced it. Do not create issues; this pass reports only (no issue-creating tool is declared, so it cannot). End your reply with the report.
"""
+4
View File
@@ -88,7 +88,9 @@
"/news/archie/1.57.0/": "/news/1.57.0/",
"/news/archie/1.58.0/": "/news/1.58.0/",
"/news/archie/1.58.1/": "/news/1.58.1/",
"/news/archie/1.59.0/": "/news/1.59.0/",
"/news/archie/1.6.0/": "/news/1.6.0/",
"/news/archie/1.60.0/": "/news/1.60.0/",
"/news/archie/1.7.0/": "/news/1.7.0/",
"/news/archie/1.8.0/": "/news/1.8.0/",
"/news/archie/1.9.0/": "/news/1.9.0/",
@@ -192,7 +194,9 @@
"/news/archied/1.57.0/": "/news/1.57.0/",
"/news/archied/1.58.0/": "/news/1.58.0/",
"/news/archied/1.58.1/": "/news/1.58.1/",
"/news/archied/1.59.0/": "/news/1.59.0/",
"/news/archied/1.6.0/": "/news/1.6.0/",
"/news/archied/1.60.0/": "/news/1.60.0/",
"/news/archied/1.7.0/": "/news/1.7.0/",
"/news/archied/1.8.0/": "/news/1.8.0/",
"/news/archied/1.9.0/": "/news/1.9.0/",
+10
View File
@@ -1,4 +1,14 @@
[
{
"version": "1.60.0",
"date": "2026-11-02",
"body": "### archied\n\n- Curators can list a repository's open issues and file new ones with the `issue_list` and `issue_create` tools, which reach the forge through the daemon. A curator files only when its definition declares `issue_create`; the shipped self-intake example runs in dry run with `issue_list` for deduplication. Listing every open issue needs the forge extensions from the archipelago release after 1.2.0."
},
{
"version": "1.59.0",
"date": "2026-11-02",
"body": "### archied\n\n- Forge extensions can open issues: the forge surface gains `CreateIssue` alongside list, comment and close, and the bundled Gitea and GitHub extensions implement it."
},
{
"version": "1.58.1",
"date": "2026-11-01",
+68
View File
@@ -0,0 +1,68 @@
# Self-development loop: archie develops its own codebase
**Status:** Decided, not yet built (2026-11-03, sam) **Scope:** how archie
persistently takes on development of archie-core itself. This file records a
desired state, not an implementation or a product: nothing below exists unless
the "Built today" section says so. The plan is tracked as epic #1769 with child
issues #1770–#1775. This file is a record, not a mechanism: agents only see
what is in their context, so verify every claim here against the code before
acting on it — where they disagree, the code wins. The boundary below is
load-bearing only where it is enforced (the gate, access control, the daemon's
git monopoly) and stated in `AGENTS.md`; everywhere else this file is a pointer.
## Built today
The machinery the loop will reuse exists: shipped triage/implement/pr-review
workflows, the adversarial self-review stage before a PR opens (epic #1348,
closed), the prbench judge for review quality with its acceptance bar, canary
releases judged on the installed release (releaseupdate), and the curator
engine. What does not exist is the loop itself: no self-intake curator, no
approved-issue auto-run, no judge for diffs, no outcome distillation, no
canary routing specific to self-directed changes.
## Decision
Archie improves its own codebase through a closed loop, built in stages:
1. **Self-intake** (#1770): a curator pass reads run outcomes, step transcripts,
gate failures and alerts, dedupes against open issues, and files new issues.
Archie files its own work; the maintainer approves priority.
2. **Approved-issue loop** (#1771): an approved issue runs the shipped
triage/implement workflows end to end — read-only plan, gated build,
adversarial self-review, daemon commits and opens a green PR. The maintainer
still merges at this stage.
3. **Implementation judge** (#1772): the prbench judge pattern scores diffs,
calibrated against the maintainer's merge decisions; auto-merge applies only
when the gate is green, the review stage is clean, and the judge is above the
calibrated bar.
4. **Outcome distillation** (#1773): a curator turns merged-run postmortems into
proposals for the repo's agent instructions, each added only because it
changes a decision; rules that stop changing decisions are removed.
5. **Canary** (#1774): self-directed changes ship through the canary release
window and are judged on the installed release before promotion. Rollback is
a plain revert, because every self-directed change is one gated commit.
## Boundary
Enforcement lives in the harness, never in the prompt (#1775). Changes to the
commit gate, the invariants in `AGENTS.md`, access control and grant scoping,
the daemon-only git path, and webhook HMAC verification may be proposed by
archie but are never merged by archie — they require a maintainer merge.
Everything else (workflows, curators, memory, docs, the dashboard) is fair game
for the loop.
## Why
Self-improvement degrades when it relies on the model choosing to follow rules.
Gates, scoped grants and the daemon's monopoly on git cannot be argued with; a
prompt can. Keeping quality measurable — a judge bar and a canary verdict as
numbers, tests guarding the protected seams — is what lets the loop widen
without turning the codebase to garbage.
## Consequences
- One issue → one small PR applies doubly to self-directed work: past about 100
lines or any new mechanism, the change stops and reassesses.
- Every self-directed commit cites the issue that authorized it.
- Rule proposals from the distillation curator must name the run that triggered
them, and `AGENTS.md` stays short enough to read in full every session.
+2 -2
View File
@@ -35,8 +35,8 @@ module.exports = async ({ page, go, shot, settled }) => {
assert.ok(await skip.evaluate(el => el === document.activeElement), 'Skip link is not the first keyboard stop');
await page.keyboard.press('Enter');
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content');
await page.getByRole('button', { name: 'Sections', exact: true }).click();
await page.getByRole('navigation', { name: 'Sections', exact: true }).getByRole('link', { name: 'Tasks', exact: true }).click();
await page.getByRole('button', { name: 'Toggle Sidebar', exact: true }).click();
await page.getByRole('list', { name: 'Sections', exact: true }).getByRole('link', { name: 'Tasks', exact: true }).click();
await page.waitForFunction(() => document.activeElement?.id === 'main-content', null, { timeout: 5000 }).catch(() => {});
assert.equal(await page.evaluate(() => document.activeElement?.id), 'main-content', 'route navigation did not focus main');
await page.getByRole('button', { name: 'Jump to', exact: true }).click();
+6 -5
View File
@@ -1,4 +1,4 @@
// The topbar org selector: choosing a member org reloads the dashboard into it,
// The sidebar org switcher: choosing a member org reloads the dashboard into it,
// Tasks and Workflows then show only that org's work, and the API refuses an
// org the caller is not a member of.
const assert = require('node:assert/strict');
@@ -8,11 +8,12 @@ module.exports = async ({ page, go, shot, settled, tolerate }) => {
tolerate(ABSENT);
await go('/tasks');
await page.getByText('Fix flaky login test').first().waitFor();
const picker = page.getByRole('combobox', { name: 'Organisation' });
const picker = page.getByRole('button', { name: /^Organisation: / });
await picker.waitFor();
const offered = await (async () => {
await picker.click();
const names = await page.getByRole('option').allInnerTexts();
await page.getByRole('menuitem').first().waitFor();
const names = (await page.getByRole('menuitem').allInnerTexts()).map(t => t.trim().split('\n').pop().trim());
await page.keyboard.press('Escape');
return names;
})();
@@ -22,9 +23,9 @@ module.exports = async ({ page, go, shot, settled, tolerate }) => {
await shot('home-org-workflows');
await picker.click();
await Promise.all([page.waitForEvent('load'), page.getByRole('option', { name: 'Beta', exact: true }).click()]);
await Promise.all([page.waitForEvent('load'), page.getByRole('menuitem', { name: 'Beta' }).click()]);
await settled('/workflows');
await page.getByRole('combobox', { name: 'Organisation' }).waitFor();
await page.getByRole('button', { name: /^Organisation: / }).waitFor();
assert.equal(await page.getByText('Parked', { exact: true }).count(), 0, 'workflow run counts leaked across orgs');
await shot('beta-workflows');
await go('/tasks');
+22
View File
@@ -50,6 +50,7 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore"
"github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
"github.com/samcharles93/archie-core/internal/infrastructure/extension"
"github.com/samcharles93/archie-core/internal/infrastructure/issuerpc"
"github.com/samcharles93/archie-core/internal/infrastructure/kitrun"
"github.com/samcharles93/archie-core/internal/infrastructure/logrpc"
"github.com/samcharles93/archie-core/internal/infrastructure/messagingrpc"
@@ -587,9 +588,30 @@ func (b *boot) registerNATSRPC() error {
return err
}
b.addCleanup(unsubscribeTaskActions)
unsubscribeIssues, err := (&issuerpc.Server{Forge: b.issueForge, Allowed: b.managedRepository, Log: log}).Register(coreConn)
if err != nil {
log.Error("issue RPC register failed", "err", err)
return err
}
b.addCleanup(unsubscribeIssues)
return nil
}
// issueForge is the instance forge, or nil while none is configured.
func (b *boot) issueForge() forge.IssueForge {
if b.forgeClient == nil {
return nil
}
return b.forgeClient
}
// managedRepository refuses a repository the organisation has not added.
func (b *boot) managedRepository(ctx context.Context, owner, repo string) error {
_, err := b.repositoryBinding(ctx, owner, repo)
return err
}
func (b *boot) buildDaemon() {
log := b.log
b.d = &daemon.Daemon{
+5 -2
View File
@@ -19,8 +19,11 @@ const releaseUsage = `usage: archied release <command>
keygen -seed FILE write a new signing key's seed to FILE and print its public key
publish sign a release and push it to a release source's next channel
promote -version V point stable at a published release by hand
canary start point the canary at next and install a release on it
canary check judge the release on next and promote it or roll the canary back`
canary status show the canary's channel, installed release, window and verdict (read-only)
canary start point the canary at next and install a release on it, queued behind one being judged
canary check judge the release the canary runs: promote it, pick up a newer next, or roll back
canary promote promote the release the canary runs now, if its signals pass
canary unpin return the canary to the next channel from any pin`
// RunRelease is the publisher's side of a release source: it makes the key
// a source signs with and pushes signed releases to it.
+549 -87
View File
@@ -25,129 +25,505 @@ const canaryInstallWait = 20 * time.Minute
const migrationsDir = "internal/infrastructure/postgres/migrations"
func runReleaseCanary(args []string, out, stderr io.Writer) int {
if len(args) == 0 || (args[0] != "start" && args[0] != "check") {
if len(args) == 0 {
fmt.Fprintln(stderr, releaseUsage)
return 2
}
flags := flag.NewFlagSet("release canary "+args[0], flag.ContinueOnError)
switch args[0] {
case "status":
return runCanaryStatus(args[1:], out, stderr)
case "start":
return runCanaryStart(args[1:], out, stderr)
case "check":
return runCanaryCheck(args[1:], out, stderr)
case "promote":
return runCanaryPromote(args[1:], out, stderr)
case "unpin":
return runCanaryUnpin(args[1:], out, stderr)
default:
fmt.Fprintln(stderr, releaseUsage)
return 2
}
}
// addCanaryFlags registers the flags every canary subcommand takes.
func addCanaryFlags(flags *flag.FlagSet) (dashboardURL, tokenEnv *string) {
dashboardURL = flags.String("dashboard", "", "canary dashboard URL")
tokenEnv = flags.String("token-env", "ARCHIE_CANARY_TOKEN", "environment variable holding a dashboard API token for the canary")
return dashboardURL, tokenEnv
}
// addSourceFlags registers the flags naming the release source.
func addSourceFlags(flags *flag.FlagSet) (reference, key *string) {
reference = flags.String("source", "", "OCI repository releases are published to; blank is the official releases")
key = flags.String("key", "", "base64 ed25519 public key the source signs with")
return reference, key
}
func canaryDashboard(url, tokenEnv string) (releaseupdate.CanaryDashboard, error) {
if url == "" {
return releaseupdate.CanaryDashboard{}, errors.New("-dashboard is required")
}
return releaseupdate.CanaryDashboard{URL: url, Token: os.Getenv(tokenEnv)}, nil
}
func canarySource(reference, key string) (distribution.Source, error) {
return distribution.Parse(reference, key, distribution.DefaultReleases())
}
// fetchChannel fetches a channel tag; found is false when the channel has no
// release yet.
func fetchChannel(ctx context.Context, source distribution.Source, tag string) (release releaseupdate.Release, found bool, err error) {
release, err = releaseupdate.Fetch(ctx, source, tag)
if errors.Is(err, errdef.ErrNotFound) {
return releaseupdate.Release{}, false, nil
}
return release, err == nil, err
}
// publishedChannels are the releases the source currently publishes.
type publishedChannels struct {
next, stable releaseupdate.Release
hasNext, hasStable bool
}
func fetchChannels(ctx context.Context, source distribution.Source) (publishedChannels, error) {
var channels publishedChannels
var err error
if channels.next, channels.hasNext, err = fetchChannel(ctx, source, "next"); err != nil {
return channels, err
}
if channels.stable, channels.hasStable, err = fetchChannel(ctx, source, "stable"); err != nil {
return channels, err
}
return channels, nil
}
// canaryRun is the release the canary actually runs: its version, when it was
// installed and its fetched release statement.
type canaryRun struct {
version string
installedAt time.Time
release releaseupdate.Release
found bool
}
// readCanaryRun reads what the canary runs. A host that doesn't record install
// times (it updated before they were tracked) degrades to the release
// statement's issue time.
func readCanaryRun(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source) (canaryRun, error) {
var run canaryRun
version, installedAt, _, err := dashboard.Installed(ctx)
if err != nil {
return run, err
}
run.version, run.installedAt = version, installedAt
release, found, err := fetchChannel(ctx, source, releaseupdate.Tag("exact-pin", version))
if err != nil {
return run, err
}
run.release, run.found = release, found
if run.installedAt.IsZero() && found {
run.installedAt = release.Statement.IssuedAt
}
return run, nil
}
// newerIssued reports whether release a was issued after b. IssuedAt, not
// semver order: Promote refuses a release issued before the one stable names,
// so the judge must agree with that replay rule.
func newerIssued(a, b releaseupdate.Release) bool {
return a.Statement.IssuedAt.After(b.Statement.IssuedAt)
}
func displayVersion(version string) string {
if version == "" {
return "unknown"
}
return version
}
func displayRelease(release releaseupdate.Release, found bool) string {
if !found {
return "none"
}
return release.Statement.Version
}
func printVerdict(out io.Writer, version string, verdict releaseupdate.CanaryVerdict) {
fmt.Fprintf(out, "%s: %s\n", displayVersion(version), verdict.Decision)
for _, reason := range verdict.Reasons {
fmt.Fprintf(out, " %s\n", reason)
}
}
func runCanaryStatus(args []string, out, stderr io.Writer) int {
flags := flag.NewFlagSet("release canary status", flag.ContinueOnError)
flags.SetOutput(stderr)
dashboardURL := flags.String("dashboard", "", "canary dashboard URL")
tokenEnv := flags.String("token-env", "ARCHIE_CANARY_TOKEN", "environment variable holding a dashboard API token for the canary")
version := flags.String("version", "", "release to install (start)")
reference := flags.String("source", "", "OCI repository releases are published to; blank is the official releases (check)")
key := flags.String("key", "", "base64 ed25519 public key the source signs with (check)")
latest := flags.String("latest", "", "comma-separated image repositories whose v<version> tag becomes latest on promotion (check)")
checkout := flags.String("checkout", ".", "repository checkout with release tags, to see whether a release migrated the database (check)")
if err := flags.Parse(args[1:]); err != nil {
dashboardURL, tokenEnv := addCanaryFlags(flags)
reference, key := addSourceFlags(flags)
window := flags.Duration("window", releaseupdate.CanaryWindow, "window a release is judged over, counted from its install")
if err := flags.Parse(args); err != nil {
return 2
}
dashboard := releaseupdate.CanaryDashboard{URL: *dashboardURL, Token: os.Getenv(*tokenEnv)}
if *dashboardURL == "" {
fmt.Fprintln(stderr, "release canary: -dashboard is required")
return 2
}
ctx := context.Background()
if args[0] == "start" {
if *version == "" {
fmt.Fprintln(stderr, "release canary start: -version is required")
return 2
}
if err := startCanary(ctx, dashboard, *version); err != nil {
fmt.Fprintln(stderr, err)
return 1
}
fmt.Fprintf(out, "canary follows next and runs %s\n", *version)
return 0
}
source, err := distribution.Parse(*reference, *key, distribution.DefaultReleases())
dashboard, err := canaryDashboard(*dashboardURL, *tokenEnv)
if err != nil {
fmt.Fprintln(stderr, "release canary check:", err)
fmt.Fprintln(stderr, "release canary status:", err)
return 2
}
rolledBack, err := checkCanary(ctx, dashboard, source, splitList(*latest), *checkout, out)
source, err := canarySource(*reference, *key)
if err != nil {
fmt.Fprintln(stderr, err)
return 1
fmt.Fprintln(stderr, "release canary status:", err)
return 2
}
if rolledBack {
if err := printCanaryStatus(context.Background(), dashboard, source, *window, out); err != nil {
fmt.Fprintln(stderr, "release canary status:", err)
return 1
}
return 0
}
func startCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, version string) error {
if err := dashboard.Follow(ctx, "next", ""); err != nil {
return fmt.Errorf("point the canary at next: %w", err)
}
return dashboard.Install(ctx, version, canaryInstallWait)
}
// checkCanary judges the release on the next channel once and acts on the
// result. It reports rolledBack so that the caller can fail the run.
func checkCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, latest []string, checkout string, out io.Writer) (rolledBack bool, err error) {
next, err := releaseupdate.Fetch(ctx, source, "next")
if err != nil {
return false, err
}
stable, err := releaseupdate.Fetch(ctx, source, "stable")
hasStable := err == nil
if err != nil && !errors.Is(err, errdef.ErrNotFound) {
return false, err
}
release := next.Statement
if release.Prerelease || (hasStable && !release.IssuedAt.After(stable.Statement.IssuedAt)) {
fmt.Fprintf(out, "nothing to judge: next is %s and isn't a newer release than stable\n", release.Version)
return false, nil
}
// printCanaryStatus reports the canary's channel, installed release, the
// published channels, window progress and the verdict the current signals
// would give, without acting on anything.
func printCanaryStatus(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, window time.Duration, out io.Writer) error {
channel, pin, err := dashboard.Channel(ctx)
if err != nil {
return false, err
return err
}
if channel != "next" {
fmt.Fprintf(out, "nothing to judge: the canary is held on %s %s\n", channel, pin)
return false, nil
channels, err := fetchChannels(ctx, source)
if err != nil {
return err
}
run, err := readCanaryRun(ctx, dashboard, source)
if err != nil {
return err
}
printCanaryState(out, channel, pin, run, channels, window)
return printCanaryVerdict(ctx, dashboard, run, window, out)
}
func printCanaryState(out io.Writer, channel, pin string, run canaryRun, channels publishedChannels, window time.Duration) {
fmt.Fprintf(out, "channel: %s\n", channelDisplay(channel, pin))
fmt.Fprintf(out, "installed: %s", displayVersion(run.version))
if run.installedAt.IsZero() {
fmt.Fprintln(out, " (installed_at not reported)")
} else {
fmt.Fprintf(out, " since %s\n", run.installedAt.Format(time.RFC3339))
}
fmt.Fprintf(out, "stable: %s\n", displayRelease(channels.stable, channels.hasStable))
fmt.Fprintf(out, "next: %s\n", displayRelease(channels.next, channels.hasNext))
if run.installedAt.IsZero() {
fmt.Fprintln(out, "window: unknown, no install time to count from")
} else {
elapsed := time.Since(run.installedAt)
fmt.Fprintf(out, "window: %s of %s elapsed since the install\n", elapsed.Round(time.Minute), window)
}
}
func printCanaryVerdict(ctx context.Context, dashboard releaseupdate.CanaryDashboard, run canaryRun, window time.Duration, out io.Writer) error {
if run.installedAt.IsZero() {
fmt.Fprintln(out, "verdict: unknown, no install time to judge from")
return nil
}
now := time.Now().UTC()
signals, err := dashboard.Signals(ctx, release.IssuedAt, now)
signals, err := dashboard.Signals(ctx, run.installedAt, now, window)
if err != nil {
return false, fmt.Errorf("read canary signals: %w", err)
return fmt.Errorf("read canary signals: %w", err)
}
verdict := releaseupdate.JudgeCanary(release.Version, now.Sub(release.IssuedAt), signals)
fmt.Fprintf(out, "%s: %s\n", release.Version, verdict.Decision)
printSignals(out, signals)
verdict := releaseupdate.JudgeCanary(run.version, run.installedAt, now, window, signals)
fmt.Fprintf(out, "verdict on %s: %s (read-only)\n", displayVersion(run.version), verdict.Decision)
for _, reason := range verdict.Reasons {
fmt.Fprintf(out, " %s\n", reason)
}
switch verdict.Decision {
case releaseupdate.CanaryPromote:
if _, err := releaseupdate.Promote(ctx, source.Reference, source.Key, release.Version, latest); err != nil {
return false, fmt.Errorf("promote %s: %w", release.Version, err)
return nil
}
func printSignals(out io.Writer, s releaseupdate.CanarySignals) {
fmt.Fprintf(out, "signals: runs %q, ready=%t, new action alerts=%d\n", s.Installed, s.Ready, len(s.NewActionAlerts))
fmt.Fprintf(out, " tasks finished %d, parked or died %d (baseline %d, %d)\n",
s.Canary.Finished, s.Canary.Bad, s.Baseline.Finished, s.Baseline.Bad)
fmt.Fprintf(out, " error lines %d, log covers %s (baseline %d, covers %s)\n",
s.Canary.Errors, s.Canary.Covered.Round(time.Minute), s.Baseline.Errors, s.Baseline.Covered.Round(time.Minute))
}
func channelDisplay(channel, pin string) string {
if pin != "" {
return channel + " (pinned to " + pin + ")"
}
return channel
}
func runCanaryStart(args []string, out, stderr io.Writer) int {
flags := flag.NewFlagSet("release canary start", flag.ContinueOnError)
flags.SetOutput(stderr)
dashboardURL, tokenEnv := addCanaryFlags(flags)
reference, key := addSourceFlags(flags)
version := flags.String("version", "", "release to install on the canary")
force := flags.Bool("force", false, "install even when the canary is still judging a newer release")
if err := flags.Parse(args); err != nil {
return 2
}
dashboard, err := canaryDashboard(*dashboardURL, *tokenEnv)
if err != nil {
fmt.Fprintln(stderr, "release canary start:", err)
return 2
}
if *version == "" {
fmt.Fprintln(stderr, "release canary start: -version is required")
return 2
}
source, err := canarySource(*reference, *key)
if err != nil {
fmt.Fprintln(stderr, "release canary start:", err)
return 2
}
if err := startCanary(context.Background(), dashboard, source, *version, *force, out); err != nil {
fmt.Fprintln(stderr, "release canary start:", err)
return 1
}
return 0
}
// startCanary points the canary at next — clearing any rollback pin — and
// installs version on it. A release published while the canary still judges a
// newer one queues behind it, so the running window isn't restarted under a
// different release.
func startCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, version string, force bool, out io.Writer) error {
// The channel is read before following next: a canary already on next is
// judging the release it runs, and a new release queues behind that one.
channel, _, err := dashboard.Channel(ctx)
if err != nil {
return err
}
if err := dashboard.Follow(ctx, "next", ""); err != nil {
return fmt.Errorf("point the canary at next: %w", err)
}
if !force {
queued, err := queuedBehind(ctx, dashboard, source, channel, version, out)
if err != nil {
return err
}
fmt.Fprintf(out, "stable is %s\n", release.Version)
if queued {
return nil
}
}
if err := dashboard.Install(ctx, version, canaryInstallWait); err != nil {
return err
}
fmt.Fprintf(out, "the canary follows next and runs %s\n", version)
return nil
}
// queuedBehind reports whether version must wait: the canary already follows
// next and is still judging the release it runs (a judgeable one), which is a
// different release from version.
func queuedBehind(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, channel, version string, out io.Writer) (bool, error) {
if channel != "next" {
return false, nil
case releaseupdate.CanaryRollBack:
return true, rollBackCanary(ctx, dashboard, release.Version, stable.Statement.Version, hasStable, checkout, out)
}
run, err := readCanaryRun(ctx, dashboard, source)
if err != nil {
return false, err
}
if run.version == version {
return false, nil
}
channels, err := fetchChannels(ctx, source)
if err != nil {
return false, err
}
if judgeable(run, channels) {
fmt.Fprintf(out, "%s is queued behind %s, which the canary is still judging\n", version, run.version)
return true, nil
}
return false, nil
}
// rollBackCanary pins the canary to the stable release and reinstalls it.
// Going back past a migration needs the pre-update database snapshot, which
// loses every write since, so a release that migrated is held instead.
func rollBackCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, failed, stable string, hasStable bool, checkout string, out io.Writer) error {
if !hasStable || migrated(ctx, checkout, stable, failed) {
if err := dashboard.Follow(ctx, "exact-pin", failed); err != nil {
return fmt.Errorf("hold the canary on %s: %w", failed, err)
func runCanaryCheck(args []string, out, stderr io.Writer) int {
flags := flag.NewFlagSet("release canary check", flag.ContinueOnError)
flags.SetOutput(stderr)
dashboardURL, tokenEnv := addCanaryFlags(flags)
reference, key := addSourceFlags(flags)
latest := flags.String("latest", "", "comma-separated image repositories whose v<version> tag becomes latest on promotion")
checkout := flags.String("checkout", ".", "repository checkout with release tags, to see whether a release migrated the database")
window := flags.Duration("window", releaseupdate.CanaryWindow, "window the installed release is judged over, counted from its install")
if err := flags.Parse(args); err != nil {
return 2
}
dashboard, err := canaryDashboard(*dashboardURL, *tokenEnv)
if err != nil {
fmt.Fprintln(stderr, "release canary check:", err)
return 2
}
source, err := canarySource(*reference, *key)
if err != nil {
fmt.Fprintln(stderr, "release canary check:", err)
return 2
}
code, err := checkCanary(context.Background(), dashboard, source, splitList(*latest), *checkout, *window, out)
if err != nil {
fmt.Fprintln(stderr, "release canary check:", err)
return 1
}
return code
}
// checkCanary judges the release the canary actually runs — not the moving
// next tag — and acts on the verdict. The exit code is 1 when the run should
// show red: a rollback happened, or the canary is held on a pin that can no
// longer be installed.
func checkCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, latest []string, checkout string, window time.Duration, out io.Writer) (int, error) {
channels, err := fetchChannels(ctx, source)
if err != nil {
return 1, err
}
channel, pin, err := dashboard.Channel(ctx)
if err != nil {
return 1, err
}
if channel != "next" {
return heldCanary(ctx, source, channel, pin, out)
}
run, err := readCanaryRun(ctx, dashboard, source)
if err != nil {
return 1, err
}
if !judgeable(run, channels) {
fmt.Fprintf(out, "nothing to judge: the canary runs %s\n", displayVersion(run.version))
return pickupNext(ctx, dashboard, channels, run.version, out)
}
return judgeInstalled(ctx, dashboard, source, run, channels, latest, checkout, window, out)
}
// judgeable reports whether the installed release is one the canary judges: a
// published, non-prerelease release issued after stable's.
func judgeable(run canaryRun, channels publishedChannels) bool {
if !run.found || run.release.Statement.Prerelease {
return false
}
return !channels.hasStable || newerIssued(run.release, channels.stable)
}
func judgeInstalled(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, run canaryRun, channels publishedChannels, latest []string, checkout string, window time.Duration, out io.Writer) (int, error) {
now := time.Now().UTC()
signals, err := dashboard.Signals(ctx, run.installedAt, now, window)
if err != nil {
return 1, fmt.Errorf("read canary signals: %w", err)
}
verdict := releaseupdate.JudgeCanary(run.version, run.installedAt, now, window, signals)
printVerdict(out, run.version, verdict)
switch verdict.Decision {
case releaseupdate.CanaryPromote:
return 0, promoteJudged(ctx, dashboard, source, run, channels, latest, out)
case releaseupdate.CanaryRollBack:
return 1, rollBackCanary(ctx, dashboard, source, run, channels, checkout, out)
default:
return 0, nil
}
}
// promoteJudged moves stable to the judged release, then picks up a newer next
// queued behind it.
func promoteJudged(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, run canaryRun, channels publishedChannels, latest []string, out io.Writer) error {
if _, err := releaseupdate.Promote(ctx, source.Reference, source.Key, run.version, latest); err != nil {
return fmt.Errorf("promote %s: %w", run.version, err)
}
fmt.Fprintf(out, "stable is %s\n", run.version)
fresh := channels
fresh.stable, fresh.hasStable = run.release, true
_, err := pickupNext(ctx, dashboard, fresh, run.version, out)
return err
}
// pickupNext installs the next release when it is newer than stable and the
// canary doesn't already run it.
func pickupNext(ctx context.Context, dashboard releaseupdate.CanaryDashboard, channels publishedChannels, installed string, out io.Writer) (int, error) {
if !channels.hasNext || channels.next.Statement.Version == installed {
return 0, nil
}
if channels.hasStable && !newerIssued(channels.next, channels.stable) {
return 0, nil
}
if err := dashboard.Install(ctx, channels.next.Statement.Version, canaryInstallWait); err != nil {
return 1, err
}
fmt.Fprintf(out, "the canary picks up %s from next\n", channels.next.Statement.Version)
return 0, nil
}
// heldCanary reports a canary that isn't following next. Its pin must still be
// installable: a stranded pin fails the run instead of looking green.
func heldCanary(ctx context.Context, source distribution.Source, channel, pin string, out io.Writer) (int, error) {
if pin != "" {
err := checkPin(ctx, source, pin)
if errors.Is(err, errStrandedPin) {
fmt.Fprintf(out, "ERROR: the canary is held on %s %s, which is stranded: %v; unpin it or republish the release\n", channel, pin, err)
return 1, nil
}
fmt.Fprintf(out, "%s changed the database schema or there's no stable release to return to: the canary is held on %s and stable is unchanged; fix forward\n", failed, failed)
return nil
if err != nil {
return 1, err
}
fmt.Fprintf(out, "held on %s %s, nothing to judge\n", channel, pin)
return 0, nil
}
if err := dashboard.Follow(ctx, "exact-pin", stable); err != nil {
return fmt.Errorf("pin the canary to %s: %w", stable, err)
fmt.Fprintf(out, "held on %s, nothing to judge\n", channel)
return 0, nil
}
// errStrandedPin marks a held pin that can no longer be installed.
var errStrandedPin = errors.New("pin is stranded")
// checkPin fails when a held pin can no longer be installed: the release is
// gone from the source, or its artifacts are.
func checkPin(ctx context.Context, source distribution.Source, pin string) error {
release, found, err := fetchChannel(ctx, source, releaseupdate.Tag("exact-pin", pin))
if err != nil {
return err
}
if err := dashboard.Install(ctx, stable, canaryInstallWait); err != nil {
return fmt.Errorf("return the canary to %s: %w", stable, err)
if !found {
return fmt.Errorf("%w: no release %s in the source", errStrandedPin, releaseupdate.Tag("exact-pin", pin))
}
fmt.Fprintf(out, "the canary is back on %s and stable is unchanged\n", stable)
if err := releaseupdate.Installable(ctx, source, release); err != nil {
return fmt.Errorf("%w: %w", errStrandedPin, err)
}
return nil
}
// rollBackCanary returns the canary to stable after a failed verdict. stable
// is checked installable before the canary is pinned to it: a pin whose
// artifacts are gone would strand the canary, so the run fails loudly and the
// canary stays on next. A release that changed the migrations is held on the
// failed version instead, because going back past a migration needs the
// pre-update database snapshot.
func rollBackCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, run canaryRun, channels publishedChannels, checkout string, out io.Writer) error {
failed := run.version
if !channels.hasStable {
return holdCanary(ctx, dashboard, failed, "there's no stable release to return to", out)
}
stable := channels.stable
if err := releaseupdate.Installable(ctx, source, stable); err != nil {
return fmt.Errorf("stable %s is not installable, the canary stays on next: %w", stable.Statement.Version, err)
}
if migrated(ctx, checkout, stable.Statement.Version, failed) {
return holdCanary(ctx, dashboard, failed, failed+" changed the database schema", out)
}
if err := dashboard.Follow(ctx, "exact-pin", stable.Statement.Version); err != nil {
return fmt.Errorf("pin the canary to %s: %w", stable.Statement.Version, err)
}
if err := dashboard.Install(ctx, stable.Statement.Version, canaryInstallWait); err != nil {
return fmt.Errorf("return the canary to %s: %w", stable.Statement.Version, err)
}
fmt.Fprintf(out, "the canary is back on %s and stable is unchanged\n", stable.Statement.Version)
return nil
}
func holdCanary(ctx context.Context, dashboard releaseupdate.CanaryDashboard, version, why string, out io.Writer) error {
if err := dashboard.Follow(ctx, "exact-pin", version); err != nil {
return fmt.Errorf("hold the canary on %s: %w", version, err)
}
fmt.Fprintf(out, "%s: the canary is held on %s and stable is unchanged; fix forward\n", why, version)
return nil
}
@@ -158,3 +534,89 @@ func migrated(ctx context.Context, checkout, from, to string) bool {
err := exec.CommandContext(ctx, "git", "-C", checkout, "diff", "--quiet", "v"+from, "v"+to, "--", migrationsDir).Run()
return err != nil
}
func runCanaryPromote(args []string, out, stderr io.Writer) int {
flags := flag.NewFlagSet("release canary promote", flag.ContinueOnError)
flags.SetOutput(stderr)
dashboardURL, tokenEnv := addCanaryFlags(flags)
reference, key := addSourceFlags(flags)
latest := flags.String("latest", "", "comma-separated image repositories whose v<version> tag becomes latest on promotion")
version := flags.String("version", "", "release expected on the canary; must match what it runs")
window := flags.Duration("window", releaseupdate.CanaryWindow, "window the signals are read over, counted from the install")
if err := flags.Parse(args); err != nil {
return 2
}
dashboard, err := canaryDashboard(*dashboardURL, *tokenEnv)
if err != nil {
fmt.Fprintln(stderr, "release canary promote:", err)
return 2
}
source, err := canarySource(*reference, *key)
if err != nil {
fmt.Fprintln(stderr, "release canary promote:", err)
return 2
}
code, err := promoteCanaryNow(context.Background(), dashboard, source, *version, splitList(*latest), *window, out)
if err != nil {
fmt.Fprintln(stderr, "release canary promote:", err)
return 1
}
return code
}
// promoteCanaryNow promotes the release the canary runs right now, without
// waiting out the window: the signals must show no hard failure and no
// relative breach. It refuses, with exit 1, when anything fails.
func promoteCanaryNow(ctx context.Context, dashboard releaseupdate.CanaryDashboard, source distribution.Source, expectVersion string, latest []string, window time.Duration, out io.Writer) (int, error) {
run, err := readCanaryRun(ctx, dashboard, source)
if err != nil {
return 1, err
}
channel, pin, err := dashboard.Channel(ctx)
if err != nil {
return 1, err
}
fmt.Fprintf(out, "channel: %s\n", channelDisplay(channel, pin))
if expectVersion != "" && expectVersion != run.version {
return 1, fmt.Errorf("the canary runs %s, not %s", displayVersion(run.version), expectVersion)
}
if !run.found {
return 1, fmt.Errorf("no release %s in the source to promote", displayVersion(run.version))
}
now := time.Now().UTC()
signals, err := dashboard.Signals(ctx, run.installedAt, now, window)
if err != nil {
return 1, fmt.Errorf("read canary signals: %w", err)
}
verdict := releaseupdate.JudgeCanaryNow(run.version, now, window, signals)
printVerdict(out, run.version, verdict)
if verdict.Decision == releaseupdate.CanaryRollBack {
fmt.Fprintln(out, "refusing to promote: the canary's signals fail")
return 1, nil
}
if _, err := releaseupdate.Promote(ctx, source.Reference, source.Key, run.version, latest); err != nil {
return 1, fmt.Errorf("promote %s: %w", run.version, err)
}
fmt.Fprintf(out, "stable is %s\n", run.version)
return 0, nil
}
func runCanaryUnpin(args []string, out, stderr io.Writer) int {
flags := flag.NewFlagSet("release canary unpin", flag.ContinueOnError)
flags.SetOutput(stderr)
dashboardURL, tokenEnv := addCanaryFlags(flags)
if err := flags.Parse(args); err != nil {
return 2
}
dashboard, err := canaryDashboard(*dashboardURL, *tokenEnv)
if err != nil {
fmt.Fprintln(stderr, "release canary unpin:", err)
return 2
}
if err := dashboard.Follow(context.Background(), "next", ""); err != nil {
fmt.Fprintln(stderr, "release canary unpin:", err)
return 1
}
fmt.Fprintln(out, "the canary follows next again, with no pin")
return 0
}
+1 -4
View File
@@ -295,10 +295,7 @@ func hasConfigSection(document map[string]any, section string) bool {
}
func updateStateDir() string {
if dir := os.Getenv("ARCHIE_UPDATE_STATE_DIR"); dir != "" {
return dir
}
return configuration.DefaultUpdateStateDir()
return configuration.UpdateStateDir()
}
// resumeUpdate hands an interrupted transaction to the frozen watchdog and
+39 -1
View File
@@ -12,7 +12,9 @@ import (
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore"
@@ -40,7 +42,7 @@ func (b *server) setupCurators(ctx context.Context) bool {
MemoryEngines: b.memEngines,
Skills: skillcurator.NewStore(skillsRoot),
Conversations: sessioncurator.NewAdapter(b.chatSessionStore, b.cfg.BotUser),
LLM: curatorLLMRunner{llm: b.chatLLM, outcomes: b.providerOutcomes, usage: b.usage},
LLM: actingPrincipalRunner{inner: curatorLLMRunner{llm: b.chatLLM, outcomes: b.providerOutcomes, usage: b.usage}, resolve: b.actingPrincipal},
Model: model,
})
@@ -95,6 +97,42 @@ func (s curatorEventSink) Emit(kind, detail string, data map[string]any) {
s.b.Publish(context.Background(), events.Event{Kind: kind, Detail: detail, Data: data})
}
// actingPrincipal resolves the identity the instance acts as for automated
// work (the default chat identity, falling back to the bot user), so curator
// passes authorize guarded tools exactly as that identity would.
func (b *server) actingPrincipal(ctx context.Context) (access.Principal, error) {
name := b.defaultChatIdentity
if name == "" {
name = b.cfg.BotUser
}
if name == "" {
return access.Principal{}, fmt.Errorf("no acting identity configured (chat identity or bot user)")
}
idn, err := b.stateStore.ResolveLegacyName(ctx, name)
if err != nil {
return access.Principal{}, fmt.Errorf("resolve acting identity %q: %w", name, err)
}
return b.stateStore.PrincipalFor(ctx, idn.ID)
}
// actingPrincipalRunner attaches the acting principal to every curator model
// call. Tool handlers run in the call's context, so guarded tools see the
// curator as the instance's identity, never as an anonymous or caller-supplied
// one; a pass that cannot resolve the principal fails closed.
type actingPrincipalRunner struct {
inner curator.LLMRunner
resolve func(context.Context) (access.Principal, error)
}
func (r actingPrincipalRunner) Chat(ctx context.Context, req curator.ChatRequest) (curator.ChatResult, error) {
p, err := r.resolve(ctx)
if err != nil {
return curator.ChatResult{}, fmt.Errorf("curator pass: %w", err)
}
ctx = org.WithScope(org.WithOrg(access.WithPrincipal(ctx, p), p.Org), p.Org)
return r.inner.Chat(ctx, req)
}
// curatorLLMRunner adapts the shared ai-sdk runtime to the curator
// family's narrow LLMRunner contract: one model reference, plain
// messages, and the declared tool set -- no streaming. Tools are built
+9
View File
@@ -18,6 +18,7 @@ import (
"github.com/samcharles93/archie-core/internal/gateway"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
"github.com/samcharles93/archie-core/internal/infrastructure/issuerpc"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/infrastructure/taskmcp"
"github.com/samcharles93/archie-core/internal/plugin"
@@ -109,6 +110,14 @@ func (b *server) registerWorkflowTools(ctx context.Context) {
authz := infraaccess.StartLive(ctx, b.stateStore.ListPolicies, b.stateStore.PoliciesVersion, b.log)
workflows := controlplanerpc.NewWorkflows(b.stateStore.ControlPlane())
entries := append(gateway.WorkflowTools(workflows, authz), gateway.IntegrationTools(integrationSource{Workflows: workflows, store: b.stateStore}, authz)...)
// Run-inspection tools back long-running curators (self-intake first);
// the State Store client satisfies the source directly.
entries = append(entries, gateway.RunTools(b.stateStore, authz)...)
// Issue tools reach the forge through the daemon, which alone holds its
// credentials; without the broker connection they are not registered.
if b.taskActionsConn != nil {
entries = append(entries, gateway.IssueTools(issuerpc.Client{Conn: b.taskActionsConn, Timeout: 30 * time.Second}, authz)...)
}
for _, entry := range entries {
if err := b.toolReg.Register(entry); err != nil {
b.log.WarnContext(ctx, "workflow tool registration failed", "tool", entry.Name, "err", err)
File diff suppressed because it is too large. Load diff
@@ -23,6 +23,7 @@ const (
ForgeService_AssignedIssues_FullMethodName = "/forge.v1.ForgeService/AssignedIssues"
ForgeService_IssuesWithLabel_FullMethodName = "/forge.v1.ForgeService/IssuesWithLabel"
ForgeService_Comment_FullMethodName = "/forge.v1.ForgeService/Comment"
ForgeService_CreateIssue_FullMethodName = "/forge.v1.ForgeService/CreateIssue"
ForgeService_CloseIssue_FullMethodName = "/forge.v1.ForgeService/CloseIssue"
ForgeService_React_FullMethodName = "/forge.v1.ForgeService/React"
ForgeService_SetStateLabel_FullMethodName = "/forge.v1.ForgeService/SetStateLabel"
@@ -60,6 +61,7 @@ type ForgeServiceClient interface {
AssignedIssues(ctx context.Context, in *AssignedIssuesRequest, opts ...grpc.CallOption) (*AssignedIssuesResponse, error)
IssuesWithLabel(ctx context.Context, in *IssuesWithLabelRequest, opts ...grpc.CallOption) (*IssuesWithLabelResponse, error)
Comment(ctx context.Context, in *CommentRequest, opts ...grpc.CallOption) (*CommentResponse, error)
CreateIssue(ctx context.Context, in *CreateIssueRequest, opts ...grpc.CallOption) (*CreateIssueResponse, error)
CloseIssue(ctx context.Context, in *CloseIssueRequest, opts ...grpc.CallOption) (*CloseIssueResponse, error)
React(ctx context.Context, in *ReactRequest, opts ...grpc.CallOption) (*ReactResponse, error)
SetStateLabel(ctx context.Context, in *SetStateLabelRequest, opts ...grpc.CallOption) (*SetStateLabelResponse, error)
@@ -132,6 +134,16 @@ func (c *forgeServiceClient) Comment(ctx context.Context, in *CommentRequest, op
return out, nil
}
func (c *forgeServiceClient) CreateIssue(ctx context.Context, in *CreateIssueRequest, opts ...grpc.CallOption) (*CreateIssueResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CreateIssueResponse)
err := c.cc.Invoke(ctx, ForgeService_CreateIssue_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *forgeServiceClient) CloseIssue(ctx context.Context, in *CloseIssueRequest, opts ...grpc.CallOption) (*CloseIssueResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CloseIssueResponse)
@@ -338,6 +350,7 @@ type ForgeServiceServer interface {
AssignedIssues(context.Context, *AssignedIssuesRequest) (*AssignedIssuesResponse, error)
IssuesWithLabel(context.Context, *IssuesWithLabelRequest) (*IssuesWithLabelResponse, error)
Comment(context.Context, *CommentRequest) (*CommentResponse, error)
CreateIssue(context.Context, *CreateIssueRequest) (*CreateIssueResponse, error)
CloseIssue(context.Context, *CloseIssueRequest) (*CloseIssueResponse, error)
React(context.Context, *ReactRequest) (*ReactResponse, error)
SetStateLabel(context.Context, *SetStateLabelRequest) (*SetStateLabelResponse, error)
@@ -382,6 +395,9 @@ func (UnimplementedForgeServiceServer) IssuesWithLabel(context.Context, *IssuesW
func (UnimplementedForgeServiceServer) Comment(context.Context, *CommentRequest) (*CommentResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Comment not implemented")
}
func (UnimplementedForgeServiceServer) CreateIssue(context.Context, *CreateIssueRequest) (*CreateIssueResponse, error) {
return nil, status.Error(codes.Unimplemented, "method CreateIssue not implemented")
}
func (UnimplementedForgeServiceServer) CloseIssue(context.Context, *CloseIssueRequest) (*CloseIssueResponse, error) {
return nil, status.Error(codes.Unimplemented, "method CloseIssue not implemented")
}
@@ -529,6 +545,24 @@ func _ForgeService_Comment_Handler(srv interface{}, ctx context.Context, dec fun
return interceptor(ctx, in, info, handler)
}
func _ForgeService_CreateIssue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateIssueRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ForgeServiceServer).CreateIssue(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ForgeService_CreateIssue_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ForgeServiceServer).CreateIssue(ctx, req.(*CreateIssueRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ForgeService_CloseIssue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CloseIssueRequest)
if err := dec(in); err != nil {
@@ -869,6 +903,10 @@ var ForgeService_ServiceDesc = grpc.ServiceDesc{
MethodName: "Comment",
Handler: _ForgeService_Comment_Handler,
},
{
MethodName: "CreateIssue",
Handler: _ForgeService_CreateIssue_Handler,
},
{
MethodName: "CloseIssue",
Handler: _ForgeService_CloseIssue_Handler,
File diff suppressed because it is too large. Load diff
@@ -38,6 +38,7 @@ const (
AccountService_AddPersonalToken_FullMethodName = "/state.v1.AccountService/AddPersonalToken"
AccountService_ListPersonalTokens_FullMethodName = "/state.v1.AccountService/ListPersonalTokens"
AccountService_RevokePersonalToken_FullMethodName = "/state.v1.AccountService/RevokePersonalToken"
AccountService_BindIdentityPersonalToken_FullMethodName = "/state.v1.AccountService/BindIdentityPersonalToken"
)
// AccountServiceClient is the client API for AccountService service.
@@ -65,6 +66,12 @@ type AccountServiceClient interface {
AddPersonalToken(ctx context.Context, in *AddPersonalTokenRequest, opts ...grpc.CallOption) (*AddPersonalTokenResponse, error)
ListPersonalTokens(ctx context.Context, in *ListPersonalTokensRequest, opts ...grpc.CallOption) (*ListPersonalTokensResponse, error)
RevokePersonalToken(ctx context.Context, in *RevokePersonalTokenRequest, opts ...grpc.CallOption) (*RevokePersonalTokenResponse, error)
// BindIdentityPersonalToken binds a personal token to a NAMED identity
// instead of the caller's principal, which is how a service account gets
// its bearer credential. Only non-user targets are accepted: a person's
// token comes from AddPersonalToken. The audit actor is the caller's
// principal, never a request field.
BindIdentityPersonalToken(ctx context.Context, in *BindIdentityPersonalTokenRequest, opts ...grpc.CallOption) (*BindIdentityPersonalTokenResponse, error)
}
type accountServiceClient struct {
@@ -265,6 +272,16 @@ func (c *accountServiceClient) RevokePersonalToken(ctx context.Context, in *Revo
return out, nil
}
func (c *accountServiceClient) BindIdentityPersonalToken(ctx context.Context, in *BindIdentityPersonalTokenRequest, opts ...grpc.CallOption) (*BindIdentityPersonalTokenResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(BindIdentityPersonalTokenResponse)
err := c.cc.Invoke(ctx, AccountService_BindIdentityPersonalToken_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// AccountServiceServer is the server API for AccountService service.
// All implementations must embed UnimplementedAccountServiceServer
// for forward compatibility.
@@ -290,6 +307,12 @@ type AccountServiceServer interface {
AddPersonalToken(context.Context, *AddPersonalTokenRequest) (*AddPersonalTokenResponse, error)
ListPersonalTokens(context.Context, *ListPersonalTokensRequest) (*ListPersonalTokensResponse, error)
RevokePersonalToken(context.Context, *RevokePersonalTokenRequest) (*RevokePersonalTokenResponse, error)
// BindIdentityPersonalToken binds a personal token to a NAMED identity
// instead of the caller's principal, which is how a service account gets
// its bearer credential. Only non-user targets are accepted: a person's
// token comes from AddPersonalToken. The audit actor is the caller's
// principal, never a request field.
BindIdentityPersonalToken(context.Context, *BindIdentityPersonalTokenRequest) (*BindIdentityPersonalTokenResponse, error)
mustEmbedUnimplementedAccountServiceServer()
}
@@ -357,6 +380,9 @@ func (UnimplementedAccountServiceServer) ListPersonalTokens(context.Context, *Li
func (UnimplementedAccountServiceServer) RevokePersonalToken(context.Context, *RevokePersonalTokenRequest) (*RevokePersonalTokenResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RevokePersonalToken not implemented")
}
func (UnimplementedAccountServiceServer) BindIdentityPersonalToken(context.Context, *BindIdentityPersonalTokenRequest) (*BindIdentityPersonalTokenResponse, error) {
return nil, status.Error(codes.Unimplemented, "method BindIdentityPersonalToken not implemented")
}
func (UnimplementedAccountServiceServer) mustEmbedUnimplementedAccountServiceServer() {}
func (UnimplementedAccountServiceServer) testEmbeddedByValue() {}
@@ -720,6 +746,24 @@ func _AccountService_RevokePersonalToken_Handler(srv interface{}, ctx context.Co
return interceptor(ctx, in, info, handler)
}
func _AccountService_BindIdentityPersonalToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BindIdentityPersonalTokenRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AccountServiceServer).BindIdentityPersonalToken(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: AccountService_BindIdentityPersonalToken_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AccountServiceServer).BindIdentityPersonalToken(ctx, req.(*BindIdentityPersonalTokenRequest))
}
return interceptor(ctx, in, info, handler)
}
// AccountService_ServiceDesc is the grpc.ServiceDesc for AccountService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -803,6 +847,10 @@ var AccountService_ServiceDesc = grpc.ServiceDesc{
MethodName: "RevokePersonalToken",
Handler: _AccountService_RevokePersonalToken_Handler,
},
{
MethodName: "BindIdentityPersonalToken",
Handler: _AccountService_BindIdentityPersonalToken_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "state/v1/account.proto",
+59
View File
@@ -0,0 +1,59 @@
package access
import "github.com/samcharles93/archie-core/internal/domain/org"
// CanaryGrantID is the ID the canary's scoped grant is known by in the policy
// store and in denial records. A stored policy must not reuse it: the store's
// seeding and the reset command overwrite shipped IDs, and this one is
// installed by the operator from CanaryGrantPolicy's text.
const CanaryGrantID = "org-canary-grant"
// CanaryGrantForbidID is the matching forbid's ID: the grant only scopes the
// canary if everything else it could reach is forbidden, because the identity
// may also carry a role (API-created service accounts are assigned developer)
// whose shipped policy permits broadly within the org. A forbid wins within
// the level, so the pair scopes the identity regardless of its role.
const CanaryGrantForbidID = "org-canary-grant-forbid"
// canaryGrantActions is the exact action surface the canary needs, as one
// Cedar condition shared by the grant's permit and its forbid.
func canaryGrantActions() string {
return `(
(action == Archie::Action::"read" && ["dashboard", "task"].contains(resource.kind)) ||
(action == Archie::Action::"read" && resource == Archie::Object::"update-settings") ||
(action == Archie::Action::"update" && resource == Archie::Object::"update") ||
(action == Archie::Action::"manage_identities" && resource == Archie::Object::"update-settings")
)`
}
func canaryPrincipal(identityID string) string {
return `principal == Archie::Identity::"` + identityID + `"`
}
// CanaryGrantPolicy is the grant a CI canary carries instead of instance
// admin: exactly one named identity may read the dashboard's signal surface
// (chat update, alerts, logs, tasks), read and write the update-settings
// resource, and trigger an update install or deferral. Install it together
// with CanaryGrantForbidPolicy, which forbids the same identity from
// everything else. Every clause is guarded by the resource belonging to the
// principal's own org, which the engine enforces structurally anyway.
func CanaryGrantPolicy(orgID org.OrgID, identityID string) Policy {
text := `permit(principal, action, resource) when {
resource.org == principal.org &&
` + canaryPrincipal(identityID) + ` &&
` + canaryGrantActions() + `
};`
return Policy{ID: CanaryGrantID, Level: LevelOrg, OrgID: orgID, Text: text}
}
// CanaryGrantForbidPolicy forbids the canary identity from everything outside
// CanaryGrantPolicy's surface, so a role assigned to the identity (service
// accounts created through the API carry developer) cannot widen it.
func CanaryGrantForbidPolicy(orgID org.OrgID, identityID string) Policy {
text := `forbid(principal, action, resource) when {
resource.org == principal.org &&
` + canaryPrincipal(identityID) + ` &&
!` + canaryGrantActions() + `
};`
return Policy{ID: CanaryGrantForbidID, Level: LevelOrg, OrgID: orgID, Text: text}
}
+54
View File
@@ -0,0 +1,54 @@
package access
import (
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// TestCanaryGrantPolicy pins the shape of the canary grant: it names exactly
// the one identity it is built for, scoped to the org it serves, so a token
// carrying it cannot act as anyone else or reach another org.
func TestCanaryGrantPolicy(t *testing.T) {
p := CanaryGrantPolicy(org.DefaultOrgID, "canary-svc")
if err := p.Validate(); err != nil {
t.Fatalf("Validate: %v", err)
}
if p.ID != CanaryGrantID || p.Level != LevelOrg || p.OrgID != org.DefaultOrgID {
t.Fatalf("policy = %+v, want ID %q at org level in %q", p, CanaryGrantID, org.DefaultOrgID)
}
if !strings.Contains(p.Text, `principal == Archie::Identity::"canary-svc"`) {
t.Fatalf("text does not name the canary identity:\n%s", p.Text)
}
other := CanaryGrantPolicy(org.DefaultOrgID, "another")
if strings.Contains(other.Text, "canary-svc") || !strings.Contains(other.Text, `Archie::Identity::"another"`) {
t.Fatalf("grant for another identity must name that identity only:\n%s", other.Text)
}
}
// TestCanaryGrantForbidPolicy pins the forbid that keeps a role assigned to
// the canary identity from widening the grant: it names the same identity and
// negates exactly the permit's action surface.
func TestCanaryGrantForbidPolicy(t *testing.T) {
permit := CanaryGrantPolicy(org.DefaultOrgID, "canary-svc")
forbid := CanaryGrantForbidPolicy(org.DefaultOrgID, "canary-svc")
if err := forbid.Validate(); err != nil {
t.Fatalf("Validate: %v", err)
}
if forbid.ID != CanaryGrantForbidID || forbid.Level != LevelOrg || forbid.OrgID != org.DefaultOrgID {
t.Fatalf("forbid = %+v, want ID %q at org level in %q", forbid, CanaryGrantForbidID, org.DefaultOrgID)
}
if !strings.HasPrefix(forbid.Text, "forbid(") {
t.Fatalf("forbid text must be a forbid:\n%s", forbid.Text)
}
if !strings.Contains(forbid.Text, `principal == Archie::Identity::"canary-svc"`) {
t.Fatalf("forbid does not name the canary identity:\n%s", forbid.Text)
}
// The forbid must negate the permit's surface, not the permit itself.
permitBody := strings.TrimSuffix(strings.SplitN(permit.Text, "when {", 2)[1], "};")
forbidBody := strings.TrimSuffix(strings.SplitN(forbid.Text, "when {", 2)[1], "};")
if !strings.Contains(forbidBody, "!"+canaryGrantActions()) {
t.Fatalf("forbid does not negate the grant's action surface:\npermit:%s\nforbid:%s", permitBody, forbidBody)
}
}
+13 -1
View File
@@ -13,6 +13,10 @@ import (
// registry's activity surface and events.
const ActionToolCalled = "tool.called"
// ActionSummary is the Action.Type recorded for the pass's final text: the
// report a definition pass produces, kept inspectable in the activity trail.
const ActionSummary = "pass.summary"
// defaultDefinitionMaxSteps bounds the model/tool loop of one definition pass.
const defaultDefinitionMaxSteps = 10
@@ -84,7 +88,7 @@ func (e *DefinitionEngine) Pass(ctx context.Context, in PassInput) (PassResult,
return PassResult{}, err
}
actions := make([]Action, 0, len(res.ToolCalls))
actions := make([]Action, 0, len(res.ToolCalls)+1)
for _, call := range res.ToolCalls {
actions = append(actions, Action{
At: e.host.Clock.Now(),
@@ -93,6 +97,14 @@ func (e *DefinitionEngine) Pass(ctx context.Context, in PassInput) (PassResult,
Reason: in.Reason,
})
}
if summary := strings.TrimSpace(res.Text); summary != "" {
actions = append(actions, Action{
At: e.host.Clock.Now(),
Type: ActionSummary,
Detail: summary,
Reason: in.Reason,
})
}
return PassResult{Actions: actions}, nil
}
@@ -139,3 +139,31 @@ func TestInstructionOnlyRegistrarViewFiltered(t *testing.T) {
t.Error("registrar view has no clock; time is always bound")
}
}
// TestDefinitionPassRecordsSummary pins that a pass's final text is recorded
// as a pass.summary action, so a definition's report stays inspectable in the
// activity trail instead of being dropped when the model returns.
func TestDefinitionPassRecordsSummary(t *testing.T) {
llm := &fakeLLM{}
registry := NewRegistry(fullHost(llm))
engine := NewDefinitionEngine(instructionOnlyDefinition())
if err := registry.Register(engine); err != nil {
t.Fatal(err)
}
res, err := engine.Pass(t.Context(), PassInput{Reason: "test"})
if err != nil {
t.Fatalf("pass: %v", err)
}
var summary *Action
for i, a := range res.Actions {
if a.Type == ActionSummary {
summary = &res.Actions[i]
}
}
if summary == nil {
t.Fatalf("no %s action recorded; actions: %+v", ActionSummary, res.Actions)
}
if summary.Detail != "done" {
t.Errorf("summary detail = %q, want the model's final text %q", summary.Detail, "done")
}
}
+87
View File
@@ -0,0 +1,87 @@
package storecontract
import (
"context"
"time"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
// BindingStore persists bindings and their draft -> pending_approval ->
// armed states.
type BindingStore interface {
InsertBinding(ctx context.Context, b binding.Binding) (string, error)
GetBinding(ctx context.Context, id string) (*binding.Binding, error)
ListBindings(ctx context.Context) ([]binding.Binding, error)
UpdateBinding(ctx context.Context, b binding.Binding) error
DeleteBinding(ctx context.Context, id string) error
ApproveBinding(ctx context.Context, id string) error
PauseBinding(ctx context.Context, id string) error
ResumeBinding(ctx context.Context, id string) error
}
// DispatchLedger reads the binding dispatch ledger.
type DispatchLedger interface {
// ListDispatches returns the newest ledger rows matching filter.
ListDispatches(ctx context.Context, filter DispatchFilter) ([]Dispatch, error)
}
// Dispatch is one binding/capture ledger row: the task it started, or the
// reason it started none.
type Dispatch struct {
BindingID string `json:"binding_id"`
BindingVersion int64 `json:"binding_version"`
CaptureID string `json:"capture_id"`
TaskID int64 `json:"task_id,omitempty"`
Reason string `json:"reason,omitempty"`
DispatchedAt time.Time `json:"dispatched_at"`
}
// DispatchFilter narrows ListDispatches; empty fields match any row.
type DispatchFilter struct {
BindingID string
CaptureID string
TaskID int64
Limit int
}
// BindingDispatcher looks up armed bindings, lists undispatched captures and
// records dispatches.
type BindingDispatcher interface {
ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error)
RecordDispatch(
ctx context.Context,
bindingID string,
bindingVersion int64,
captureID string,
// taskID addresses the SQLite-owned task tables, which are not
// migrating: it stays an integer on purpose. A dispatch that starts
// a task is recorded by EnqueueBindingTask instead.
taskID int64,
// reason is empty for a dispatch and names the terminal outcome of
// an evaluation that started no task.
reason string,
) error
ListUndispatchedCaptures(ctx context.Context, bindings []string, limit int) ([]CapturedEvent, error)
}
// BindingTaskCreator is the single-method consumer-facing surface for
// enqueueing a task triggered by a binding. Splitting it off TaskLifecycle
// keeps the lifecycle surface narrow (8 methods, the interfacebloat limit)
// and keeps the binding-specific shape on the binding interfaces.
type BindingTaskCreator interface {
// EnqueueBindingTask claims the binding's dispatch of captureID in the
// ledger, enqueues the task and records its provenance as one unit: an
// error leaves none of them, and a delivery already dispatched for the
// binding returns ErrAlreadyDispatched.
EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int, captureID string, inputs map[string]any) (*task.Task, error)
}
// PlaybookDispatcher records a playbook action dispatch before its side
// effect runs, returning ErrAlreadyDispatched for a duplicate.
// DeletePlaybookDispatches deletes one playbook's records.
type PlaybookDispatcher interface {
RecordPlaybookDispatch(ctx context.Context, playbookID, playbookVersion, eventID, actionID string) error
DeletePlaybookDispatches(ctx context.Context, playbookID string) error
}
+73
View File
@@ -0,0 +1,73 @@
package storecontract
import (
"context"
"time"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
)
// CaptureStore persists inbound webhook captures.
type CaptureStore interface {
InsertCapture(ctx context.Context, c CapturedEvent, retention time.Duration, maxEvents int) (string, error)
ListCaptures(ctx context.Context, limit int) ([]CapturedEvent, error)
}
// CaptureRefusalStore counts the events network rules refused, per source.
type CaptureRefusalStore interface {
RecordCaptureRefusal(ctx context.Context, source, addr string, at time.Time) error
CaptureRefusals(ctx context.Context, since time.Time) ([]CaptureRefusals, error)
}
// CaptureRefusals is one source's refusals and accepted captures since a
// time, and the addresses it refused.
type CaptureRefusals struct {
Source string `json:"source"`
Refused int64 `json:"refused"`
Accepted int64 `json:"accepted"`
Addrs []string `json:"addrs"`
}
// EventTypeStore persists event types. Insert and Update refuse a type whose
// rule overlaps another on the same source with eventtype.ErrOverlap, and a
// malformed one with eventtype.ErrInvalid. Update rewrites the name and rule;
// the schema is the one the type was created with.
type EventTypeStore interface {
InsertEventType(ctx context.Context, t eventtype.EventType) (string, error)
UpdateEventType(ctx context.Context, t eventtype.EventType) error
DeleteEventType(ctx context.Context, id string) error
ListEventTypes(ctx context.Context) ([]eventtype.EventType, error)
}
// CapturedEvent is one unbound inbound webhook capture: no workflow binding,
// no forge/task association -- just what arrived, from where, and when.
type CapturedEvent struct {
ID string `json:"id"`
ReceivedAt time.Time `json:"received_at"`
Source string `json:"source"`
RemoteAddr string `json:"remote_addr"`
ContentType string `json:"content_type"`
// Headers and Body are redacted (webhookguard.RedactPayload) before
// they ever reach InsertCapture; the store persists what it is given.
Headers string `json:"headers"`
Body string `json:"body"`
Authenticated bool `json:"authenticated"`
// EventType is the ID of the event type the capture was identified as
// when it arrived, or empty when it matched none. An unidentified capture
// is never dispatched.
EventType string `json:"event_type"`
// Unsigned marks an event that arrived on an approved unsigned source.
// It dispatches without Authenticated and is flagged wherever it shows.
Unsigned bool `json:"unsigned"`
// Delivery names the sender's delivery; a retry of one delivery shares
// it, so a binding dispatches each delivery once. Intake sets it from the
// source's delivery header; the store fills the capture ID when empty.
Delivery string `json:"delivery"`
// OrgID is honoured only for a schedule-fired capture, whose source is
// reserved and so names no org; every other capture takes its source's.
OrgID string `json:"org_id,omitempty"`
}
// Dispatchable reports whether a binding may start a task from this event:
// a valid signature, or a source approved to take unsigned events.
func (c CapturedEvent) Dispatchable() bool { return c.Authenticated || c.Unsigned }
@@ -0,0 +1,25 @@
package storecontract
import (
"context"
"time"
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
)
// HarnessSecretStore stores one org's OAuth token set per credential binding
// service, encrypted at rest.
type HarnessSecretStore interface {
GetHarnessSecret(ctx context.Context, org, service string) (harnesssecret.Secret, error)
PutHarnessSecret(ctx context.Context, s harnesssecret.Secret) error
}
// RunCredentialStore keeps run credentials by digest: the SHA-256 of the
// token a task's container presents. A lookup of an unknown or expired
// digest reports ErrRunCredentialUnknown.
type RunCredentialStore interface {
PutRunCredential(ctx context.Context, digest [32]byte, taskID int64, expires time.Time) error
DeleteRunCredential(ctx context.Context, digest [32]byte) error
RunCredentialTask(ctx context.Context, digest [32]byte, now time.Time) (int64, error)
DeleteExpiredRunCredentials(ctx context.Context, now time.Time) error
}
+90
View File
@@ -0,0 +1,90 @@
package storecontract
import (
"errors"
)
// Sentinel errors, part of the wire contract: staterpc's
// mapError/unmapError match these by (code, canonical message) across the
// gRPC boundary, so their message strings are load-bearing and must never
// change.
var (
// ErrStaleTransition is returned when a task transition's expected
// from status does not match the task's current status.
ErrStaleTransition = errors.New("store: stale transition: task status does not match expected from status")
// ErrIllegalTransition is returned when the transition table does not allow
// the status pair.
ErrIllegalTransition = errors.New("store: illegal transition: status pair is not in the transition table")
// ErrInvalidStep is returned when a step-execution request names a kind the
// store does not record or a step whose identifying fields do not resolve.
// Distinct from the transition sentinels, which cover a row's state.
ErrInvalidStep = errors.New("store: invalid step execution request")
// ErrResumeIncomplete is returned when a retry resumes after a stage whose
// last run did not complete, so there are no results to start from.
ErrResumeIncomplete = errors.New("store: the step before the resume point did not complete in its last run")
// ErrBindingNotFound is returned when a binding ID does not exist.
ErrBindingNotFound = errors.New("store: binding not found")
// ErrBindingOverlap is returned when a binding's matcher overlaps an
// existing binding for the same source.
ErrBindingOverlap = errors.New("store: binding overlaps existing binding for source")
// ErrBindingTransition is returned when a binding state transition is
// rejected by the draft -> pending_approval -> armed machine.
ErrBindingTransition = errors.New("store: binding state transition rejected")
// ErrAlreadyDispatched is returned when a dispatch ledger already holds the
// key.
ErrAlreadyDispatched = errors.New("store: binding already dispatched for capture")
// ErrCallNotYours is returned when a workflow.call status read names a
// task that is not a callee of the calling task, or the caller itself
// does not exist: a caller reads only the tasks it started
ErrCallNotYours = errors.New("store: task is not a callee of the calling task")
// ErrCallCallerNotRunning is returned when a workflow.call enqueue names
// a caller that is not running: a stale retry, or a bug in the caller.
ErrCallCallerNotRunning = errors.New("store: workflow.call caller is not running")
// ErrCallDepthExceeded is returned when a workflow.call enqueue would
// pass workflow.MaxCallDepth. The engine refuses the same call first;
// the store re-checks because it owns the table.
ErrCallDepthExceeded = errors.New("store: workflow.call would pass the depth limit")
// ErrMappingNotFound is returned when a mapping ID does not exist.
ErrMappingNotFound = errors.New("store: mapping not found")
// ErrEventTypeNotFound is returned when an event type ID does not exist.
ErrEventTypeNotFound = errors.New("store: event type not found")
// ErrSourceNotFound is returned when a source path does not exist.
ErrSourceNotFound = errors.New("store: source not found")
// ErrSourceInUse is returned when deleting a source an armed binding
// fires on.
ErrSourceInUse = errors.New("store: source has an armed binding")
// ErrSourcePathTaken is returned when a new source's path is in use.
ErrSourcePathTaken = errors.New("store: source path already taken")
// ErrSourceSigningStale is returned when a signing write's expected
// from state does not match the stored one.
ErrSourceSigningStale = errors.New("store: source signing does not match expected state")
// ErrHarnessSecretNotFound is returned when no OAuth token set is
// stored for an org/service pair -- the setup terminal has not
// captured one yet.
ErrHarnessSecretNotFound = errors.New("store: harness secret not found")
// ErrRereviewCapReached is returned when a review gate re-review would
// round past prreview.MaxRereviewRounds. The task stays waiting and its
// gate row is unchanged. The dashboard answers it 409, like every other
// conflict.
ErrRereviewCapReached = errors.New("store: re-review cap reached")
// ErrResourceNotFound is returned when a control-plane resource kind has
// no stored document. It is in-process only (not on the gRPC wire): the
// control plane runs in the daemon against the local store.
ErrResourceNotFound = errors.New("resource not found")
// ErrResourceVersionConflict is returned when a resource write carries an
// expected version that does not match the stored revision.
ErrResourceVersionConflict = errors.New("resource version conflict")
)
// ErrUnavailable means the store could not serve a request now: it is
// restarting or unreachable. It is not paired with a canonical message the way
// the sentinels above are -- staterpc derives it from the Unavailable code
// alone, whose text varies by transport -- and it is the one store error a
// caller with budget may answer by retrying rather than by failing its own
// work. The wrapping keeps the gRPC status code readable through the chain.
var ErrUnavailable = errors.New("store: state store unavailable")
// ErrRunCredentialUnknown is a run credential that was never issued, was
// revoked, or has expired.
var ErrRunCredentialUnknown = errors.New("run credential unknown or expired")
+26
View File
@@ -0,0 +1,26 @@
package storecontract
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/mapping"
)
// MappingStore persists payload field mappings. Deliberately separate from
// TaskStore and CaptureStore for the same reason those are split: the
// dashboard's mapping editor should only acquire the mapping surface, not the
// full task or capture APIs. See
type MappingStore interface {
InsertMapping(ctx context.Context, m mapping.Mapping) (string, error)
GetMapping(ctx context.Context, id string) (*mapping.Mapping, error)
ListMappings(ctx context.Context) ([]mapping.Mapping, error)
UpdateMapping(ctx context.Context, m mapping.Mapping) error
DeleteMapping(ctx context.Context, id string) error
}
// MappingMatchRecorder counts the events each mapping resolved, which the
// store reports as Mapping.MatchCount and LastMatchedAt. Recording the same
// (mapping, capture) twice counts once.
type MappingMatchRecorder interface {
RecordMappingMatch(ctx context.Context, mappingID, captureID string) error
}
+50
View File
@@ -0,0 +1,50 @@
package storecontract
import (
"time"
)
// Resource is one control-plane resource document: the stored value for an
// org's kind, its revision, and the audit record written with the last write.
// Resource and ResourceWrite live here so the UI-side consumers can reference
// them without linking the PostgreSQL implementation.
type Resource struct {
OrgID string
Kind string
Value []byte
Version int64
Actor string
Source string
RequestID string
ExpectedVersion int64
CurrentVersion int64
At time.Time
}
// DefaultOrgID is the org every resource written before orgs existed belongs
// to, and the org a request that names none acts in.
const DefaultOrgID = "org-sys"
// ResourceAuditKey is the sys_audit record key of one org's resource kind. The
// default org keeps the bare kind, so audit rows written before resources were
// per-org still resolve.
func ResourceAuditKey(orgID, kind string) string {
if orgID == DefaultOrgID {
return kind
}
return orgID + "/" + kind
}
// ResourceWrite is a control-plane resource write request. ExpectedVersion is
// the optimistic-concurrency guard: a write whose expectation does not match
// the stored revision is refused with ErrResourceVersionConflict.
type ResourceWrite struct {
OrgID string
Kind string
Value []byte
Actor string
Source string
RequestID string
ExpectedVersion int64
At time.Time
}
+23
View File
@@ -0,0 +1,23 @@
package storecontract
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/source"
)
// SourceStore persists capture sources keyed by path. Secrets are encrypted
// at rest; signing transitions use an expected-from guard.
type SourceStore interface {
InsertSource(ctx context.Context, s source.Source) error
// GetSource returns (nil, nil) for an unknown path.
GetSource(ctx context.Context, path string) (*source.Source, error)
ListSources(ctx context.Context) ([]source.Source, error)
SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error
SetSourceSecret(ctx context.Context, path, secret string) error
SetSourceName(ctx context.Context, path, name string) error
SetSourceDeliveryHeader(ctx context.Context, path, header string) error
// DeleteSource refuses with ErrSourceInUse while an armed binding fires
// on the source.
DeleteSource(ctx context.Context, path string) error
}
+87
View File
@@ -0,0 +1,87 @@
package storecontract
import (
"context"
"time"
"github.com/samcharles93/archie-core/internal/domain/health"
)
// ConfigSnapshotStore holds the published configuration view.
type ConfigSnapshotStore interface {
PutConfigSnapshot(ctx context.Context, snapshot ConfigSnapshot) error
ConfigSnapshot(ctx context.Context) (ConfigSnapshot, bool, error)
}
// ChannelStatusStore holds channel runtime state published by the process
// hosting the channels.
type ChannelStatusStore interface {
// PutChannelStatus records the reporting process's whole set: a channel it no
// longer reports is removed rather than left behind, because a stale "running"
// row is a lie the dashboard would show indefinitely.
PutChannelStatus(ctx context.Context, channels []ChannelStatus) error
ChannelStatus(ctx context.Context) ([]ChannelStatus, error)
}
// ApplyStatusStore holds which version of each control-plane resource each
// process is running. Same split as ConfigSnapshotStore and for the same
// reason: the writers are the processes that apply a resource, the reader is
// the UI, and a task-scoped credential must reach neither.
type ApplyStatusStore interface {
PutApplyStatus(ctx context.Context, status ApplyStatus) error
ListApplyStatus(ctx context.Context) ([]ApplyStatus, error)
}
// PresenceStore holds one record per running service instance. Writers are
// the services themselves; readers are the UI and archied status.
type PresenceStore interface {
PutPresence(ctx context.Context, presence Presence) error
ListPresence(ctx context.Context) ([]Presence, error)
}
// ConfigSnapshot is the published, secret-free configuration view. Schema
// names Document's shape.
type ConfigSnapshot struct {
Schema string
Document []byte
PublishedAt time.Time
}
// ChannelStatus is one channel's runtime state as the process hosting it
// reports it. ReloadSupported is a capability declaration rather than a request:
// asking for a reload travels on its own surface, because a transient request and
// a durable state do not share a lifetime.
type ChannelStatus struct {
ID string
Name string
State string
Detail string
Configured bool
ReloadSupported bool
ObservedAt time.Time
}
// ApplyStatus is one process's report on one resource kind. On error,
// AppliedVersion stays at the last applied version. ReportedAt is
// re-stamped periodically.
type ApplyStatus struct {
Process string `json:"process"`
Kind string `json:"kind"`
AppliedVersion int64 `json:"applied_version"`
Error string `json:"error,omitempty"`
ReportedAt time.Time `json:"reported_at"`
}
// Presence is one running service instance. Ready and Detail summarise its
// readiness probes; Detail names the degraded ones.
type Presence struct {
Checks []health.Component `json:"checks"`
Service string `json:"service"`
InstanceID string `json:"instance_id"`
Version string `json:"version"`
InstallType string `json:"install_type"`
StartedAt time.Time `json:"started_at"`
ReportedAt time.Time `json:"reported_at"`
Ready bool `json:"ready"`
Detail string `json:"detail,omitempty"`
}
@@ -2,23 +2,6 @@
// without an implementation.
package storecontract
import (
"context"
"errors"
"io"
"time"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/logging"
)
// TaskStore is the full store surface the daemon needs.
// Consumers depend on TaskStore, never on a concrete type.
type TaskStore interface {
@@ -31,594 +14,3 @@ type TaskStore interface {
ReviewGateResponder
RemediationStarter
}
// TaskLifecycle manages the core task state machine and enqueuing.
// Binding-triggered task creation lives on BindingTaskCreator, not here,
// so the lifecycle surface stays narrow and non-binding consumers (forge
// poll, chat spawn, drain loop) do not acquire a binding-specific shape.
type TaskLifecycle interface {
EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels, identity string) (bool, error)
EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity, origin, draft string, inputs map[string]any) (*task.Task, error)
ClaimNext(ctx context.Context) (*task.Task, error)
ClaimByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
Transition(ctx context.Context, taskID int64, from, to, detail string) error
Update(ctx context.Context, t *task.Task) error
Requeue(ctx context.Context, taskID int64, fromStatus, workflow string) error
RecoverStale(ctx context.Context) (int64, error)
}
// TaskParker parks a task with a park class and the blocker the park site
// knows, if any. Unknown classes become needs_decision.
type TaskParker interface {
ParkTask(ctx context.Context, taskID int64, from, detail, class, blocker string) error
}
// StepRecorder records a running execution's steps.
type StepRecorder interface {
StartStep(ctx context.Context, s task.StepStart) (int64, events.Event, error)
FinishStep(ctx context.Context, s task.StepFinish) (events.Event, error)
}
// ExecutionCanceller cancels an execution and its current attempt's open
// steps in one transaction. It also cancels the callees the execution was
// waiting on, and returns their ids (nested callees included) so the caller
// can stop their runs too.
type ExecutionCanceller interface {
CancelExecution(ctx context.Context, taskID int64, reason, to string) ([]int64, error)
}
// StepReader lists one execution's recorded steps.
type StepReader interface {
ListSteps(ctx context.Context, executionID int64, attempt int) ([]task.StepExecution, error)
}
// HarnessSecretStore stores one org's OAuth token set per credential binding
// service, encrypted at rest.
type HarnessSecretStore interface {
GetHarnessSecret(ctx context.Context, org, service string) (harnesssecret.Secret, error)
PutHarnessSecret(ctx context.Context, s harnesssecret.Secret) error
}
// TaskArchiver removes one terminal task's local record with an optimistic
// status guard. It is separate from the already broad lifecycle contract so
// consumers that only run tasks do not acquire an operator-only capability.
type TaskArchiver interface {
OutcomePoster
ArchiveTask(ctx context.Context, taskID int64, fromStatus string, audit events.Event) (eventID int64, err error)
ClearTerminalTasks(ctx context.Context) (int64, error)
}
// TaskRetryer atomically requeues recoverable work and accounts for the new
// attempt so a partial write cannot evade the retry cap. retryMode is the
// operator's worktree choice for the next dispatch (taskstate.RetryMode),
// persisted on the row so the daemon reads it instead of inferring it. resume
// is where the attempt starts; a resume whose After stage did not complete in
// its last run is refused with ErrResumeIncomplete.
type TaskRetryer interface {
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow, retryMode string, resume task.Resume, currentDefinition bool) error
}
// ReviewGateResponder records the operator's review-gate answer. A re-review
// increments rereview_rounds and requeues; one past the cap returns
// ErrRereviewCapReached and writes nothing.
type ReviewGateResponder interface {
RespondReviewGate(ctx context.Context, taskID int64, fromStatus, gate string, rereview bool, maxRounds int) error
}
// RemediationStarter queues a review-triggered remediation for an Archie-owned
// open-PR task: one guarded transition that carries the JSON-encoded review
// unit in the same write, so a claimed remediation always has its input. Runs
// for one task are serialised, so a distinct review that arrives while a
// remediation owns the task is queued behind it and remediated once that run
// finishes; a re-delivered unit is absorbed, not queued twice.
// UpdateReviewPayload merges late-arriving comments into the unclaimed unit
// for the same review, active or queued behind a running remediation.
type RemediationStarter interface {
BeginRemediation(ctx context.Context, taskID int64, payload string) error
UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error
// SetReviewCursors persists the poll backstop's per-task review and
// comment high-water marks (pr-review-remediation.md decision 2). The
// pr_open guard is part of the contract: cursors only move while no
// remediation run owns the task.
SetReviewCursors(ctx context.Context, taskID, reviewCursor, commentCursor int64) error
}
// OutcomePoster tracks which finished chat tasks have reported back to their
// conversation.
type OutcomePoster interface {
// UnpostedOutcomes returns finished chat tasks whose outcome has not been
// posted to the conversation that created them.
UnpostedOutcomes(ctx context.Context) ([]*task.Task, error)
// MarkOutcomePosted records that the task's state at status was posted.
MarkOutcomePosted(ctx context.Context, taskID int64, status string) error
}
// TaskQueries groups read-only task accessors.
type TaskQueries interface {
TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*task.Task, error)
TaskByID(ctx context.Context, taskID int64) (*task.Task, error)
OpenPRs(ctx context.Context) ([]task.Task, error)
// ActiveTasksByOrigin returns the queued and running tasks the
// conversation origin created, for its /stop.
ActiveTasksByOrigin(ctx context.Context, origin string) ([]*task.Task, error)
// Tasks returns the most recently updated tasks.
Tasks(ctx context.Context, limit int) ([]task.Task, error)
// TasksPage returns one page of tasks, most recently updated first.
TasksPage(ctx context.Context, page TaskPage) ([]task.Task, error)
StatusCounts(ctx context.Context) (map[string]int, error)
}
// TaskEvents groups observability and lifecycle methods.
type TaskEvents interface {
InsertEvent(ctx context.Context, e events.Event) (int64, error)
EventsSince(ctx context.Context, cursor string, limit int) ([]events.Event, error)
// TaskEvents returns a task's timeline, without agent transcripts.
TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error)
// TaskTranscript returns one attempt's agent transcript entries in order.
TaskTranscript(ctx context.Context, taskID int64, attempt int) ([]events.Event, error)
WorkflowStats(ctx context.Context) ([]WorkflowStat, error)
StageStats(ctx context.Context) ([]StageStat, error)
TokensByDay(ctx context.Context, days int) ([]DayTokens, error)
Close() error
}
// CaptureStore persists inbound webhook captures.
type CaptureStore interface {
InsertCapture(ctx context.Context, c CapturedEvent, retention time.Duration, maxEvents int) (string, error)
ListCaptures(ctx context.Context, limit int) ([]CapturedEvent, error)
}
// CaptureRefusalStore counts the events network rules refused, per source.
type CaptureRefusalStore interface {
RecordCaptureRefusal(ctx context.Context, source, addr string, at time.Time) error
CaptureRefusals(ctx context.Context, since time.Time) ([]CaptureRefusals, error)
}
// CaptureRefusals is one source's refusals and accepted captures since a
// time, and the addresses it refused.
type CaptureRefusals struct {
Source string `json:"source"`
Refused int64 `json:"refused"`
Accepted int64 `json:"accepted"`
Addrs []string `json:"addrs"`
}
// ConfigSnapshotStore holds the published configuration view.
type ConfigSnapshotStore interface {
PutConfigSnapshot(ctx context.Context, snapshot ConfigSnapshot) error
ConfigSnapshot(ctx context.Context) (ConfigSnapshot, bool, error)
}
// ChannelStatusStore holds channel runtime state published by the process
// hosting the channels.
type ChannelStatusStore interface {
// PutChannelStatus records the reporting process's whole set: a channel it no
// longer reports is removed rather than left behind, because a stale "running"
// row is a lie the dashboard would show indefinitely.
PutChannelStatus(ctx context.Context, channels []ChannelStatus) error
ChannelStatus(ctx context.Context) ([]ChannelStatus, error)
}
// ApplyStatusStore holds which version of each control-plane resource each
// process is running. Same split as ConfigSnapshotStore and for the same
// reason: the writers are the processes that apply a resource, the reader is
// the UI, and a task-scoped credential must reach neither.
type ApplyStatusStore interface {
PutApplyStatus(ctx context.Context, status ApplyStatus) error
ListApplyStatus(ctx context.Context) ([]ApplyStatus, error)
}
// PresenceStore holds one record per running service instance. Writers are
// the services themselves; readers are the UI and archied status.
type PresenceStore interface {
PutPresence(ctx context.Context, presence Presence) error
ListPresence(ctx context.Context) ([]Presence, error)
}
// MappingStore persists payload field mappings. Deliberately separate from
// TaskStore and CaptureStore for the same reason those are split: the
// dashboard's mapping editor should only acquire the mapping surface, not the
// full task or capture APIs. See
type MappingStore interface {
InsertMapping(ctx context.Context, m mapping.Mapping) (string, error)
GetMapping(ctx context.Context, id string) (*mapping.Mapping, error)
ListMappings(ctx context.Context) ([]mapping.Mapping, error)
UpdateMapping(ctx context.Context, m mapping.Mapping) error
DeleteMapping(ctx context.Context, id string) error
}
// MappingMatchRecorder counts the events each mapping resolved, which the
// store reports as Mapping.MatchCount and LastMatchedAt. Recording the same
// (mapping, capture) twice counts once.
type MappingMatchRecorder interface {
RecordMappingMatch(ctx context.Context, mappingID, captureID string) error
}
// EventTypeStore persists event types. Insert and Update refuse a type whose
// rule overlaps another on the same source with eventtype.ErrOverlap, and a
// malformed one with eventtype.ErrInvalid. Update rewrites the name and rule;
// the schema is the one the type was created with.
type EventTypeStore interface {
InsertEventType(ctx context.Context, t eventtype.EventType) (string, error)
UpdateEventType(ctx context.Context, t eventtype.EventType) error
DeleteEventType(ctx context.Context, id string) error
ListEventTypes(ctx context.Context) ([]eventtype.EventType, error)
}
// BindingStore persists bindings and their draft -> pending_approval ->
// armed states.
type BindingStore interface {
InsertBinding(ctx context.Context, b binding.Binding) (string, error)
GetBinding(ctx context.Context, id string) (*binding.Binding, error)
ListBindings(ctx context.Context) ([]binding.Binding, error)
UpdateBinding(ctx context.Context, b binding.Binding) error
DeleteBinding(ctx context.Context, id string) error
ApproveBinding(ctx context.Context, id string) error
PauseBinding(ctx context.Context, id string) error
ResumeBinding(ctx context.Context, id string) error
}
// SourceStore persists capture sources keyed by path. Secrets are encrypted
// at rest; signing transitions use an expected-from guard.
type SourceStore interface {
InsertSource(ctx context.Context, s source.Source) error
// GetSource returns (nil, nil) for an unknown path.
GetSource(ctx context.Context, path string) (*source.Source, error)
ListSources(ctx context.Context) ([]source.Source, error)
SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error
SetSourceSecret(ctx context.Context, path, secret string) error
SetSourceName(ctx context.Context, path, name string) error
SetSourceDeliveryHeader(ctx context.Context, path, header string) error
// DeleteSource refuses with ErrSourceInUse while an armed binding fires
// on the source.
DeleteSource(ctx context.Context, path string) error
}
// DispatchLedger reads the binding dispatch ledger.
type DispatchLedger interface {
// ListDispatches returns the newest ledger rows matching filter.
ListDispatches(ctx context.Context, filter DispatchFilter) ([]Dispatch, error)
}
// TaskPage selects one page of the task list. Empty Statuses matches every
// status. A zero After starts at the newest task; otherwise the page begins
// after the task it names, in (updated_at, id) descending order.
type TaskPage struct {
Statuses []string
// Workflow, when set, keeps only that workflow's tasks.
Workflow string
After TaskCursor
Limit int
}
// TaskCursor is the position of the last task a page returned.
type TaskCursor struct {
UpdatedAt time.Time
ID int64
}
// Dispatch is one binding/capture ledger row: the task it started, or the
// reason it started none.
type Dispatch struct {
BindingID string `json:"binding_id"`
BindingVersion int64 `json:"binding_version"`
CaptureID string `json:"capture_id"`
TaskID int64 `json:"task_id,omitempty"`
Reason string `json:"reason,omitempty"`
DispatchedAt time.Time `json:"dispatched_at"`
}
// DispatchFilter narrows ListDispatches; empty fields match any row.
type DispatchFilter struct {
BindingID string
CaptureID string
TaskID int64
Limit int
}
// BindingDispatcher looks up armed bindings, lists undispatched captures and
// records dispatches.
type BindingDispatcher interface {
ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error)
RecordDispatch(
ctx context.Context,
bindingID string,
bindingVersion int64,
captureID string,
// taskID addresses the SQLite-owned task tables, which are not
// migrating: it stays an integer on purpose. A dispatch that starts
// a task is recorded by EnqueueBindingTask instead.
taskID int64,
// reason is empty for a dispatch and names the terminal outcome of
// an evaluation that started no task.
reason string,
) error
ListUndispatchedCaptures(ctx context.Context, bindings []string, limit int) ([]CapturedEvent, error)
}
// BindingTaskCreator is the single-method consumer-facing surface for
// enqueueing a task triggered by a binding. Splitting it off TaskLifecycle
// keeps the lifecycle surface narrow (8 methods, the interfacebloat limit)
// and keeps the binding-specific shape on the binding interfaces.
type BindingTaskCreator interface {
// EnqueueBindingTask claims the binding's dispatch of captureID in the
// ledger, enqueues the task and records its provenance as one unit: an
// error leaves none of them, and a delivery already dispatched for the
// binding returns ErrAlreadyDispatched.
EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int, captureID string, inputs map[string]any) (*task.Task, error)
}
// WorkflowCaller starts a workflow.call callee and reads it back.
type WorkflowCaller = task.Caller
// PlaybookDispatcher records a playbook action dispatch before its side
// effect runs, returning ErrAlreadyDispatched for a duplicate.
// DeletePlaybookDispatches deletes one playbook's records.
type PlaybookDispatcher interface {
RecordPlaybookDispatch(ctx context.Context, playbookID, playbookVersion, eventID, actionID string) error
DeletePlaybookDispatches(ctx context.Context, playbookID string) error
}
// TaskLogStore reads one task attempt's log. Found=false means no log;
// ErrTaskLogsUnavailable means this process cannot read logs.
type TaskLogStore interface {
// TaskLog returns a page of one attempt's decoded log. attempt 0 selects
// the task's current attempt.
TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error)
// TaskLogContent writes one attempt's log verbatim to w, for a download.
// found is false, with a nil error, when the attempt has no log file.
TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (found bool, err error)
}
// CapturedEvent is one unbound inbound webhook capture: no workflow binding,
// no forge/task association -- just what arrived, from where, and when.
type CapturedEvent struct {
ID string `json:"id"`
ReceivedAt time.Time `json:"received_at"`
Source string `json:"source"`
RemoteAddr string `json:"remote_addr"`
ContentType string `json:"content_type"`
// Headers and Body are redacted (webhookguard.RedactPayload) before
// they ever reach InsertCapture; the store persists what it is given.
Headers string `json:"headers"`
Body string `json:"body"`
Authenticated bool `json:"authenticated"`
// EventType is the ID of the event type the capture was identified as
// when it arrived, or empty when it matched none. An unidentified capture
// is never dispatched.
EventType string `json:"event_type"`
// Unsigned marks an event that arrived on an approved unsigned source.
// It dispatches without Authenticated and is flagged wherever it shows.
Unsigned bool `json:"unsigned"`
// Delivery names the sender's delivery; a retry of one delivery shares
// it, so a binding dispatches each delivery once. Intake sets it from the
// source's delivery header; the store fills the capture ID when empty.
Delivery string `json:"delivery"`
// OrgID is honoured only for a schedule-fired capture, whose source is
// reserved and so names no org; every other capture takes its source's.
OrgID string `json:"org_id,omitempty"`
}
// Dispatchable reports whether a binding may start a task from this event:
// a valid signature, or a source approved to take unsigned events.
func (c CapturedEvent) Dispatchable() bool { return c.Authenticated || c.Unsigned }
// ConfigSnapshot is the published, secret-free configuration view. Schema
// names Document's shape.
type ConfigSnapshot struct {
Schema string
Document []byte
PublishedAt time.Time
}
// ChannelStatus is one channel's runtime state as the process hosting it
// reports it. ReloadSupported is a capability declaration rather than a request:
// asking for a reload travels on its own surface, because a transient request and
// a durable state do not share a lifetime.
type ChannelStatus struct {
ID string
Name string
State string
Detail string
Configured bool
ReloadSupported bool
ObservedAt time.Time
}
// ApplyStatus is one process's report on one resource kind. On error,
// AppliedVersion stays at the last applied version. ReportedAt is
// re-stamped periodically.
type ApplyStatus struct {
Process string `json:"process"`
Kind string `json:"kind"`
AppliedVersion int64 `json:"applied_version"`
Error string `json:"error,omitempty"`
ReportedAt time.Time `json:"reported_at"`
}
// Presence is one running service instance. Ready and Detail summarise its
// readiness probes; Detail names the degraded ones.
type Presence struct {
Checks []health.Component `json:"checks"`
Service string `json:"service"`
InstanceID string `json:"instance_id"`
Version string `json:"version"`
InstallType string `json:"install_type"`
StartedAt time.Time `json:"started_at"`
ReportedAt time.Time `json:"reported_at"`
Ready bool `json:"ready"`
Detail string `json:"detail,omitempty"`
}
// WorkflowStat is one row of the per-workflow metrics table.
type WorkflowStat struct {
Workflow string `json:"workflow"`
Runs int `json:"runs"`
Merged int `json:"merged"`
Completed int `json:"completed"`
PROpen int `json:"pr_open"`
Parked int `json:"parked"`
AvgTokens int `json:"avg_tokens"`
AvgSteps float64 `json:"avg_steps"`
TotalToken int `json:"total_tokens"`
// Running and LastStatus describe the workflow now: how many of its runs
// are working, and how its newest one ended.
Running int `json:"running"`
LastStatus string `json:"last_status"`
}
// StageStat is average stage duration and failure counts per stage.
type StageStat struct {
Workflow string `json:"workflow"`
Stage string `json:"stage"`
Runs int `json:"runs"`
AvgMs int `json:"avg_ms"`
Errors int `json:"errors"`
}
// DayTokens is token spend per UTC day.
type DayTokens struct {
Day string `json:"day"`
Tokens int `json:"tokens"`
}
// Sentinel errors, part of the wire contract: staterpc's
// mapError/unmapError match these by (code, canonical message) across the
// gRPC boundary, so their message strings are load-bearing and must never
// change.
var (
// ErrStaleTransition is returned when a task transition's expected
// from status does not match the task's current status.
ErrStaleTransition = errors.New("store: stale transition: task status does not match expected from status")
// ErrIllegalTransition is returned when the transition table does not allow
// the status pair.
ErrIllegalTransition = errors.New("store: illegal transition: status pair is not in the transition table")
// ErrInvalidStep is returned when a step-execution request names a kind the
// store does not record or a step whose identifying fields do not resolve.
// Distinct from the transition sentinels, which cover a row's state.
ErrInvalidStep = errors.New("store: invalid step execution request")
// ErrResumeIncomplete is returned when a retry resumes after a stage whose
// last run did not complete, so there are no results to start from.
ErrResumeIncomplete = errors.New("store: the step before the resume point did not complete in its last run")
// ErrBindingNotFound is returned when a binding ID does not exist.
ErrBindingNotFound = errors.New("store: binding not found")
// ErrBindingOverlap is returned when a binding's matcher overlaps an
// existing binding for the same source.
ErrBindingOverlap = errors.New("store: binding overlaps existing binding for source")
// ErrBindingTransition is returned when a binding state transition is
// rejected by the draft -> pending_approval -> armed machine.
ErrBindingTransition = errors.New("store: binding state transition rejected")
// ErrAlreadyDispatched is returned when a dispatch ledger already holds the
// key.
ErrAlreadyDispatched = errors.New("store: binding already dispatched for capture")
// ErrCallNotYours is returned when a workflow.call status read names a
// task that is not a callee of the calling task, or the caller itself
// does not exist: a caller reads only the tasks it started
ErrCallNotYours = errors.New("store: task is not a callee of the calling task")
// ErrCallCallerNotRunning is returned when a workflow.call enqueue names
// a caller that is not running: a stale retry, or a bug in the caller.
ErrCallCallerNotRunning = errors.New("store: workflow.call caller is not running")
// ErrCallDepthExceeded is returned when a workflow.call enqueue would
// pass workflow.MaxCallDepth. The engine refuses the same call first;
// the store re-checks because it owns the table.
ErrCallDepthExceeded = errors.New("store: workflow.call would pass the depth limit")
// ErrMappingNotFound is returned when a mapping ID does not exist.
ErrMappingNotFound = errors.New("store: mapping not found")
// ErrEventTypeNotFound is returned when an event type ID does not exist.
ErrEventTypeNotFound = errors.New("store: event type not found")
// ErrSourceNotFound is returned when a source path does not exist.
ErrSourceNotFound = errors.New("store: source not found")
// ErrSourceInUse is returned when deleting a source an armed binding
// fires on.
ErrSourceInUse = errors.New("store: source has an armed binding")
// ErrSourcePathTaken is returned when a new source's path is in use.
ErrSourcePathTaken = errors.New("store: source path already taken")
// ErrSourceSigningStale is returned when a signing write's expected
// from state does not match the stored one.
ErrSourceSigningStale = errors.New("store: source signing does not match expected state")
// ErrHarnessSecretNotFound is returned when no OAuth token set is
// stored for an org/service pair -- the setup terminal has not
// captured one yet.
ErrHarnessSecretNotFound = errors.New("store: harness secret not found")
// ErrRereviewCapReached is returned when a review gate re-review would
// round past prreview.MaxRereviewRounds. The task stays waiting and its
// gate row is unchanged. The dashboard answers it 409, like every other
// conflict.
ErrRereviewCapReached = errors.New("store: re-review cap reached")
// ErrResourceNotFound is returned when a control-plane resource kind has
// no stored document. It is in-process only (not on the gRPC wire): the
// control plane runs in the daemon against the local store.
ErrResourceNotFound = errors.New("resource not found")
// ErrResourceVersionConflict is returned when a resource write carries an
// expected version that does not match the stored revision.
ErrResourceVersionConflict = errors.New("resource version conflict")
)
// ErrUnavailable means the store could not serve a request now: it is
// restarting or unreachable. It is not paired with a canonical message the way
// the sentinels above are -- staterpc derives it from the Unavailable code
// alone, whose text varies by transport -- and it is the one store error a
// caller with budget may answer by retrying rather than by failing its own
// work. The wrapping keeps the gRPC status code readable through the chain.
var ErrUnavailable = errors.New("store: state store unavailable")
// Resource is one control-plane resource document: the stored value for an
// org's kind, its revision, and the audit record written with the last write.
// Resource and ResourceWrite live here so the UI-side consumers can reference
// them without linking the PostgreSQL implementation.
type Resource struct {
OrgID string
Kind string
Value []byte
Version int64
Actor string
Source string
RequestID string
ExpectedVersion int64
CurrentVersion int64
At time.Time
}
// DefaultOrgID is the org every resource written before orgs existed belongs
// to, and the org a request that names none acts in.
const DefaultOrgID = "org-sys"
// ResourceAuditKey is the sys_audit record key of one org's resource kind. The
// default org keeps the bare kind, so audit rows written before resources were
// per-org still resolve.
func ResourceAuditKey(orgID, kind string) string {
if orgID == DefaultOrgID {
return kind
}
return orgID + "/" + kind
}
// ResourceWrite is a control-plane resource write request. ExpectedVersion is
// the optimistic-concurrency guard: a write whose expectation does not match
// the stored revision is refused with ErrResourceVersionConflict.
type ResourceWrite struct {
OrgID string
Kind string
Value []byte
Actor string
Source string
RequestID string
ExpectedVersion int64
At time.Time
}
// ErrRunCredentialUnknown is a run credential that was never issued, was
// revoked, or has expired.
var ErrRunCredentialUnknown = errors.New("run credential unknown or expired")
// RunCredentialStore keeps run credentials by digest: the SHA-256 of the
// token a task's container presents. A lookup of an unknown or expired
// digest reports ErrRunCredentialUnknown.
type RunCredentialStore interface {
PutRunCredential(ctx context.Context, digest [32]byte, taskID int64, expires time.Time) error
DeleteRunCredential(ctx context.Context, digest [32]byte) error
RunCredentialTask(ctx context.Context, digest [32]byte, now time.Time) (int64, error)
DeleteExpiredRunCredentials(ctx context.Context, now time.Time) error
}
+198
View File
@@ -0,0 +1,198 @@
package storecontract
import (
"context"
"io"
"time"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/logging"
)
// TaskLifecycle manages the core task state machine and enqueuing.
// Binding-triggered task creation lives on BindingTaskCreator, not here,
// so the lifecycle surface stays narrow and non-binding consumers (forge
// poll, chat spawn, drain loop) do not acquire a binding-specific shape.
type TaskLifecycle interface {
EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels, identity string) (bool, error)
EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity, origin, draft string, inputs map[string]any) (*task.Task, error)
ClaimNext(ctx context.Context) (*task.Task, error)
ClaimByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
Transition(ctx context.Context, taskID int64, from, to, detail string) error
Update(ctx context.Context, t *task.Task) error
Requeue(ctx context.Context, taskID int64, fromStatus, workflow string) error
RecoverStale(ctx context.Context) (int64, error)
}
// TaskParker parks a task with a park class and the blocker the park site
// knows, if any. Unknown classes become needs_decision.
type TaskParker interface {
ParkTask(ctx context.Context, taskID int64, from, detail, class, blocker string) error
}
// StepRecorder records a running execution's steps.
type StepRecorder interface {
StartStep(ctx context.Context, s task.StepStart) (int64, events.Event, error)
FinishStep(ctx context.Context, s task.StepFinish) (events.Event, error)
}
// ExecutionCanceller cancels an execution and its current attempt's open
// steps in one transaction. It also cancels the callees the execution was
// waiting on, and returns their ids (nested callees included) so the caller
// can stop their runs too.
type ExecutionCanceller interface {
CancelExecution(ctx context.Context, taskID int64, reason, to string) ([]int64, error)
}
// StepReader lists one execution's recorded steps.
type StepReader interface {
ListSteps(ctx context.Context, executionID int64, attempt int) ([]task.StepExecution, error)
}
// TaskArchiver removes one terminal task's local record with an optimistic
// status guard. It is separate from the already broad lifecycle contract so
// consumers that only run tasks do not acquire an operator-only capability.
type TaskArchiver interface {
OutcomePoster
ArchiveTask(ctx context.Context, taskID int64, fromStatus string, audit events.Event) (eventID int64, err error)
ClearTerminalTasks(ctx context.Context) (int64, error)
}
// TaskRetryer atomically requeues recoverable work and accounts for the new
// attempt so a partial write cannot evade the retry cap. retryMode is the
// operator's worktree choice for the next dispatch (taskstate.RetryMode),
// persisted on the row so the daemon reads it instead of inferring it. resume
// is where the attempt starts; a resume whose After stage did not complete in
// its last run is refused with ErrResumeIncomplete.
type TaskRetryer interface {
RetryTask(ctx context.Context, taskID int64, fromStatus, workflow, retryMode string, resume task.Resume, currentDefinition bool) error
}
// ReviewGateResponder records the operator's review-gate answer. A re-review
// increments rereview_rounds and requeues; one past the cap returns
// ErrRereviewCapReached and writes nothing.
type ReviewGateResponder interface {
RespondReviewGate(ctx context.Context, taskID int64, fromStatus, gate string, rereview bool, maxRounds int) error
}
// RemediationStarter queues a review-triggered remediation for an Archie-owned
// open-PR task: one guarded transition that carries the JSON-encoded review
// unit in the same write, so a claimed remediation always has its input. Runs
// for one task are serialised, so a distinct review that arrives while a
// remediation owns the task is queued behind it and remediated once that run
// finishes; a re-delivered unit is absorbed, not queued twice.
// UpdateReviewPayload merges late-arriving comments into the unclaimed unit
// for the same review, active or queued behind a running remediation.
type RemediationStarter interface {
BeginRemediation(ctx context.Context, taskID int64, payload string) error
UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error
// SetReviewCursors persists the poll backstop's per-task review and
// comment high-water marks (pr-review-remediation.md decision 2). The
// pr_open guard is part of the contract: cursors only move while no
// remediation run owns the task.
SetReviewCursors(ctx context.Context, taskID, reviewCursor, commentCursor int64) error
}
// OutcomePoster tracks which finished chat tasks have reported back to their
// conversation.
type OutcomePoster interface {
// UnpostedOutcomes returns finished chat tasks whose outcome has not been
// posted to the conversation that created them.
UnpostedOutcomes(ctx context.Context) ([]*task.Task, error)
// MarkOutcomePosted records that the task's state at status was posted.
MarkOutcomePosted(ctx context.Context, taskID int64, status string) error
}
// TaskQueries groups read-only task accessors.
type TaskQueries interface {
TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*task.Task, error)
TaskByID(ctx context.Context, taskID int64) (*task.Task, error)
OpenPRs(ctx context.Context) ([]task.Task, error)
// ActiveTasksByOrigin returns the queued and running tasks the
// conversation origin created, for its /stop.
ActiveTasksByOrigin(ctx context.Context, origin string) ([]*task.Task, error)
// Tasks returns the most recently updated tasks.
Tasks(ctx context.Context, limit int) ([]task.Task, error)
// TasksPage returns one page of tasks, most recently updated first.
TasksPage(ctx context.Context, page TaskPage) ([]task.Task, error)
StatusCounts(ctx context.Context) (map[string]int, error)
}
// TaskEvents groups observability and lifecycle methods.
type TaskEvents interface {
InsertEvent(ctx context.Context, e events.Event) (int64, error)
EventsSince(ctx context.Context, cursor string, limit int) ([]events.Event, error)
// TaskEvents returns a task's timeline, without agent transcripts.
TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error)
// TaskTranscript returns one attempt's agent transcript entries in order.
TaskTranscript(ctx context.Context, taskID int64, attempt int) ([]events.Event, error)
WorkflowStats(ctx context.Context) ([]WorkflowStat, error)
StageStats(ctx context.Context) ([]StageStat, error)
TokensByDay(ctx context.Context, days int) ([]DayTokens, error)
Close() error
}
// TaskPage selects one page of the task list. Empty Statuses matches every
// status. A zero After starts at the newest task; otherwise the page begins
// after the task it names, in (updated_at, id) descending order.
type TaskPage struct {
Statuses []string
// Workflow, when set, keeps only that workflow's tasks.
Workflow string
After TaskCursor
Limit int
}
// TaskCursor is the position of the last task a page returned.
type TaskCursor struct {
UpdatedAt time.Time
ID int64
}
// WorkflowCaller starts a workflow.call callee and reads it back.
type WorkflowCaller = task.Caller
// TaskLogStore reads one task attempt's log. Found=false means no log;
// ErrTaskLogsUnavailable means this process cannot read logs.
type TaskLogStore interface {
// TaskLog returns a page of one attempt's decoded log. attempt 0 selects
// the task's current attempt.
TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error)
// TaskLogContent writes one attempt's log verbatim to w, for a download.
// found is false, with a nil error, when the attempt has no log file.
TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (found bool, err error)
}
// WorkflowStat is one row of the per-workflow metrics table.
type WorkflowStat struct {
Workflow string `json:"workflow"`
Runs int `json:"runs"`
Merged int `json:"merged"`
Completed int `json:"completed"`
PROpen int `json:"pr_open"`
Parked int `json:"parked"`
AvgTokens int `json:"avg_tokens"`
AvgSteps float64 `json:"avg_steps"`
TotalToken int `json:"total_tokens"`
// Running and LastStatus describe the workflow now: how many of its runs
// are working, and how its newest one ended.
Running int `json:"running"`
LastStatus string `json:"last_status"`
}
// StageStat is average stage duration and failure counts per stage.
type StageStat struct {
Workflow string `json:"workflow"`
Stage string `json:"stage"`
Runs int `json:"runs"`
AvgMs int `json:"avg_ms"`
Errors int `json:"errors"`
}
// DayTokens is token spend per UTC day.
type DayTokens struct {
Day string `json:"day"`
Tokens int `json:"tokens"`
}
+5
View File
@@ -45,6 +45,11 @@ type recordedForge struct {
deliveries Deliveries
}
func (f recordedForge) CreateIssue(ctx context.Context, owner, repo, title, _ string, _ []string) (int, error) {
f.deliveries.Record(ctx, fmt.Sprintf("open issue %q in %s/%s", title, owner, repo))
return 0, nil
}
func (f recordedForge) CloseIssue(ctx context.Context, owner, repo string, number int, _ string) error {
f.deliveries.Record(ctx, fmt.Sprintf("close issue %s/%s#%d", owner, repo, number))
return nil
+4
View File
@@ -38,6 +38,10 @@ type IssueForge interface {
// Comment posts an issue (or PR) comment and returns its id.
Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error)
// CreateIssue opens an issue with title, body and optional labels,
// returning its number.
CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error)
// CloseIssue closes an issue with an optional final comment.
CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error
+4
View File
@@ -30,6 +30,10 @@ func (n *NoopForge) Comment(ctx context.Context, owner, repo string, number int,
return 0, nil
}
func (n *NoopForge) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) {
return 0, nil
}
func (n *NoopForge) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
return nil
}
+43 -2
View File
@@ -23,6 +23,7 @@ import (
const (
SubjectComment = "archie.forge.comment"
SubjectCreateIssue = "archie.forge.create_issue"
SubjectCloseIssue = "archie.forge.close_issue"
SubjectCreatePR = "archie.forge.create_pr"
SubjectLinkBranch = "archie.forge.link_branch"
@@ -35,8 +36,9 @@ const (
// set a task of that identity may publish to.
func Subjects(identity string) []string {
bases := []string{
SubjectComment, SubjectCloseIssue, SubjectCreatePR, SubjectLinkBranch,
SubjectSetStateLabel, SubjectCreateReviewComment, SubjectReplyToReview,
SubjectComment, SubjectCreateIssue, SubjectCloseIssue, SubjectCreatePR,
SubjectLinkBranch, SubjectSetStateLabel, SubjectCreateReviewComment,
SubjectReplyToReview,
}
out := make([]string, len(bases))
for i, base := range bases {
@@ -80,6 +82,17 @@ type CommentResponse struct {
natsrpc.Envelope
}
type CreateIssueRequest struct {
Target
Title, Body string
Labels []string
}
type CreateIssueResponse struct {
Number int `json:"number"`
natsrpc.Envelope
}
type CloseIssueRequest struct {
Target
Number int
@@ -168,6 +181,7 @@ func (s *Server) RegisterFor(nc *nats.Conn, identity string) (unsubscribe func()
}
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
{Subject: serverSubject(identity, SubjectComment), Handler: as(s.handleComment)},
{Subject: serverSubject(identity, SubjectCreateIssue), Handler: as(s.handleCreateIssue)},
{Subject: serverSubject(identity, SubjectCloseIssue), Handler: as(s.handleCloseIssue)},
{Subject: serverSubject(identity, SubjectCreatePR), Handler: as(s.handleCreatePR)},
{Subject: serverSubject(identity, SubjectLinkBranch), Handler: as(s.handleLinkBranch)},
@@ -249,6 +263,21 @@ func (s *Server) handleComment(ctx context.Context, identity string, msg *nats.M
s.respond(msg, CommentResponse{ID: id, Envelope: natsrpc.NewEnvelope(err)})
}
func (s *Server) handleCreateIssue(ctx context.Context, identity string, msg *nats.Msg) {
var req CreateIssueRequest
if err := json.Unmarshal(msg.Data, &req); err != nil {
s.respond(msg, CreateIssueResponse{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode create_issue request: %w", err))})
return
}
client, err := s.authorizedForge(ctx, identity, req.Target, "comment")
if err != nil {
s.respond(msg, CreateIssueResponse{Envelope: natsrpc.NewEnvelope(err)})
return
}
number, err := client.CreateIssue(ctx, req.Owner, req.Repo, req.Title, req.Body, req.Labels)
s.respond(msg, CreateIssueResponse{Number: number, Envelope: natsrpc.NewEnvelope(err)})
}
func (s *Server) handleCloseIssue(ctx context.Context, identity string, msg *nats.Msg) {
var req CloseIssueRequest
if err := json.Unmarshal(msg.Data, &req); err != nil {
@@ -392,6 +421,18 @@ func (c *Client) Comment(ctx context.Context, owner, repo string, number int, bo
return resp.ID, nil
}
func (c *Client) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) {
req := CreateIssueRequest{Target: c.target(owner, repo), Title: title, Body: body, Labels: labels}
resp, err := natsrpc.Call[CreateIssueResponse](ctx, c.rpc(), c.subject(SubjectCreateIssue), req)
if err != nil {
return 0, err
}
if err := resp.Err(); err != nil {
return 0, err
}
return resp.Number, nil
}
func (c *Client) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
req := CloseIssueRequest{Target: c.target(owner, repo), Number: number, Comment: comment}
resp, err := natsrpc.Call[Response](ctx, c.rpc(), c.subject(SubjectCloseIssue), req)
+129
View File
@@ -0,0 +1,129 @@
package gateway
import (
"context"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/forge"
"github.com/samcharles93/archie-core/internal/tools"
)
// maxIssueListed bounds what issue_list returns, so a large backlog does not
// land in the context window whole.
const maxIssueListed = 200
// IssueSource is the forge surface the issue tools use, reached through the
// daemon.
type IssueSource interface {
OpenIssues(ctx context.Context, owner, repo string) ([]forge.Issue, error)
CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error)
}
// IssueSummary is one open issue as issue_list shows it.
type IssueSummary struct {
Number int `json:"number"`
Title string `json:"title"`
Labels []string `json:"labels,omitempty"`
}
// IssueTools returns issue_list and issue_create for curators. Filing work
// feeds the daemon's issue intake, so both are checked as acting on tasks.
// Nil source or authorizer registers none.
func IssueTools(source IssueSource, authz access.Authorizer) []tools.ToolEntry {
if source == nil || authz == nil {
return nil
}
return []tools.ToolEntry{
guarded(authz, access.ActionRead, access.KindTask, nil, issueListTool(source)),
guarded(authz, access.ActionCreate, access.KindTask, nil, issueCreateTool(source)),
}
}
var repoProperty = map[string]any{
"type": "string",
"description": "The repository as owner/name, as run_list reports it.",
}
func splitRepo(input map[string]any) (owner, repo string, err error) {
raw, _ := input["repo"].(string)
owner, repo, ok := strings.Cut(strings.TrimSpace(raw), "/")
if !ok || owner == "" || repo == "" || strings.Contains(repo, "/") {
return "", "", fmt.Errorf("repo must be owner/name")
}
return owner, repo, nil
}
func issueListTool(source IssueSource) tools.ToolEntry {
return tools.ToolEntry{
Name: "issue_list",
Toolset: "issues",
Description: "List a repository's open issues (number, title, labels). Check it before filing so you never duplicate one.",
Classification: tools.ClassIdempotent,
Schema: tools.JSONSchema{
"type": "object",
"properties": map[string]any{"repo": repoProperty},
"required": []string{"repo"},
},
Handler: func(ctx context.Context, input map[string]any) (any, error) {
owner, repo, err := splitRepo(input)
if err != nil {
return nil, fmt.Errorf("issue_list: %w", err)
}
issues, err := source.OpenIssues(ctx, owner, repo)
if err != nil {
return nil, fmt.Errorf("issue_list: %w", err)
}
out := make([]IssueSummary, 0, min(len(issues), maxIssueListed))
for _, is := range issues[:min(len(issues), maxIssueListed)] {
out = append(out, IssueSummary{Number: is.Number, Title: is.Title, Labels: is.Labels})
}
return out, nil
},
}
}
func issueCreateTool(source IssueSource) tools.ToolEntry {
return tools.ToolEntry{
Name: "issue_create",
Toolset: "issues",
Description: "File a new issue in a repository. List open issues first and file only work no open issue covers. " +
"The body must cite the run that produced it.",
Classification: tools.ClassMutating,
Schema: tools.JSONSchema{
"type": "object",
"properties": map[string]any{
"repo": repoProperty,
"title": map[string]any{"type": "string"},
"body": map[string]any{"type": "string"},
"labels": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
},
"required": []string{"repo", "title", "body"},
},
Handler: func(ctx context.Context, input map[string]any) (any, error) {
owner, repo, err := splitRepo(input)
if err != nil {
return nil, fmt.Errorf("issue_create: %w", err)
}
title, _ := input["title"].(string)
body, _ := input["body"].(string)
if strings.TrimSpace(title) == "" || strings.TrimSpace(body) == "" {
return nil, fmt.Errorf("issue_create: title and body are required")
}
var labels []string
if raw, ok := input["labels"].([]any); ok {
for _, l := range raw {
if s, ok := l.(string); ok && s != "" {
labels = append(labels, s)
}
}
}
number, err := source.CreateIssue(ctx, owner, repo, title, body, labels)
if err != nil {
return nil, fmt.Errorf("issue_create: %w", err)
}
return map[string]any{"number": number}, nil
},
}
}
+137
View File
@@ -0,0 +1,137 @@
package gateway
import (
"context"
"fmt"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/tools"
)
// RunSource is the state-store surface the run-inspection tools use. The
// State Store client satisfies it directly.
type RunSource interface {
// Tasks returns the most recently updated tasks.
Tasks(ctx context.Context, limit int) ([]task.Task, error)
// TaskEvents returns one task's events, oldest first.
TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error)
}
// RunSummary is one task as run_list shows it.
type RunSummary struct {
ID int64 `json:"id"`
Repo string `json:"repo"`
Title string `json:"title"`
Status string `json:"status"`
Workflow string `json:"workflow,omitempty"`
Issue int `json:"issue,omitempty"`
PRNumber int `json:"pr_number,omitempty"`
ParkReason string `json:"park_reason,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
// RunEvent is one task event as run_events shows it.
type RunEvent struct {
At time.Time `json:"at"`
Kind string `json:"kind"`
Stage string `json:"stage,omitempty"`
Detail string `json:"detail,omitempty"`
}
// RunTools returns the read-only run-inspection tools for long-running
// curators: what ran recently, and each run's event trail. Reads are checked
// as reading tasks, the same check the dashboard's task list gets. Nil
// source or authorizer registers none.
func RunTools(source RunSource, authz access.Authorizer) []tools.ToolEntry {
if source == nil || authz == nil {
return nil
}
read := func(entry tools.ToolEntry) tools.ToolEntry {
return guarded(authz, access.ActionRead, access.KindTask, nil, entry)
}
return []tools.ToolEntry{
read(runListTool(source)),
read(runEventsTool(source)),
}
}
func runListTool(source RunSource) tools.ToolEntry {
return tools.ToolEntry{
Name: "run_list",
Toolset: "runs",
Description: "List the most recently updated task runs across the instance, most recent first. " +
"Use it to survey what ran, what parked and why.",
Classification: tools.ClassIdempotent,
Schema: tools.JSONSchema{
"type": "object",
"properties": map[string]any{
"limit": map[string]any{
"type": "integer",
"description": fmt.Sprintf(
"Maximum runs to return. Defaults to %d, capped at %d.",
defaultTaskListLimit, maxTaskListLimit,
),
},
},
},
Handler: func(ctx context.Context, input map[string]any) (any, error) {
rows, err := source.Tasks(ctx, taskListLimit(input))
if err != nil {
return nil, fmt.Errorf("run_list: %w", err)
}
out := make([]RunSummary, 0, len(rows))
for _, t := range rows {
out = append(out, RunSummary{
ID: t.ID,
Repo: t.Owner + "/" + t.Repo,
Title: t.Title,
Status: t.Status,
Workflow: t.Workflow,
Issue: t.IssueNumber,
PRNumber: t.PRNumber,
ParkReason: t.ParkReason,
UpdatedAt: t.UpdatedAt,
})
}
return out, nil
},
}
}
func runEventsTool(source RunSource) tools.ToolEntry {
return tools.ToolEntry{
Name: "run_events",
Toolset: "runs",
Description: "List one task run's event trail, oldest first: stage transitions, deliveries, " +
"failures and park reasons. Use it to see why a run ended the way it did.",
Classification: tools.ClassIdempotent,
Schema: tools.JSONSchema{
"type": "object",
"properties": map[string]any{
"task_id": map[string]any{
"type": "integer",
"description": "The task run's ID, as run_list reports it.",
},
},
"required": []string{"task_id"},
},
Handler: func(ctx context.Context, input map[string]any) (any, error) {
id, ok := asInt64(input["task_id"])
if !ok || id <= 0 {
return nil, fmt.Errorf("run_events: task_id must be a positive integer")
}
evs, err := source.TaskEvents(ctx, id)
if err != nil {
return nil, fmt.Errorf("run_events: %w", err)
}
out := make([]RunEvent, 0, len(evs))
for _, e := range evs {
out = append(out, RunEvent{At: e.At, Kind: e.Kind, Stage: e.Stage, Detail: e.Detail})
}
return out, nil
},
}
}
@@ -112,3 +112,84 @@ func TestWorkspaceEnvironment(t *testing.T) {
})
}
}
// TestCanaryGrant pins the scoped canary grant: the one identity it names may
// read the signal surface, read and write update-settings, and trigger an
// install -- and nothing else, neither for it nor for anyone else. The canary
// principal carries the developer role (API-created service accounts are
// assigned it); the grant's forbid must keep the role from widening access.
func TestCanaryGrant(t *testing.T) {
const canaryID = identity.IdentityID("canary-svc")
grant := access.CanaryGrantPolicy(org.DefaultOrgID, string(canaryID))
forbid := access.CanaryGrantForbidPolicy(org.DefaultOrgID, string(canaryID))
engine := New(append(access.ShippedOrgPolicies(org.DefaultOrgID), grant, forbid))
if len(engine.Problems()) != 0 {
t.Fatalf("problems = %v, want the canary grant to compile", engine.Problems())
}
canary := access.Principal{
IdentityID: canaryID, Org: org.DefaultOrgID,
Memberships: []org.Membership{{IdentityID: canaryID, OrgID: org.DefaultOrgID, Role: org.RoleDeveloper}},
}
other := access.Principal{IdentityID: "someone-else", Org: org.DefaultOrgID}
at := func(kind access.ResourceKind, id string) access.Resource {
return access.Resource{Kind: kind, ID: id, Org: org.DefaultOrgID}
}
tests := []struct {
name string
principal access.Principal
action access.Action
resource access.Resource
allowed bool
}{
{"read the dashboard", canary, access.ActionRead, at(access.KindDashboard, ""), true},
{"read tasks", canary, access.ActionRead, at(access.KindTask, ""), true},
{"read one task", canary, access.ActionRead, at(access.KindTask, "7"), true},
{"read update-settings", canary, access.ActionRead, at(access.KindPolicy, "update-settings"), true},
{"install an update", canary, access.ActionUpdate, at(access.KindDashboard, "update"), true},
{"replace update-settings", canary, access.ActionManageIdentities, at(access.KindPolicy, "update-settings"), true},
{"read a secret", canary, access.ActionReadSecret, at(access.KindSecret, "github-token"), false},
{"delete a task", canary, access.ActionDelete, at(access.KindTask, "7"), false},
{"manage policies", canary, access.ActionManagePolicies, at(access.KindPolicy, "org-role-read"), false},
{"run a workflow", canary, access.ActionRun, at(access.KindWorkflow, "triage"), false},
{"create anything", canary, access.ActionCreate, at(access.KindTask, ""), false},
{"update another object", canary, access.ActionUpdate, at(access.KindDashboard, "other"), false},
{"read another object", canary, access.ActionRead, at(access.KindPolicy, "other-policy"), false},
{"manage identities on another object", canary, access.ActionManageIdentities, at(access.KindIdentity, "someone-else"), false},
{"read logs", canary, access.ActionReadLogs, at(access.KindTask, "7"), false},
{"read the audit feed", canary, access.ActionReadAudit, at(access.KindAudit, ""), false},
{"a resource of another org", canary, access.ActionRead, access.Resource{Kind: access.KindDashboard, Org: "acme"}, false},
{"another identity reads the dashboard", other, access.ActionRead, at(access.KindDashboard, ""), false},
{"another identity installs an update", other, access.ActionUpdate, at(access.KindDashboard, "update"), false},
{"another identity replaces update-settings", other, access.ActionManageIdentities, at(access.KindPolicy, "update-settings"), false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := engine.Authorize(tt.principal, tt.action, tt.resource, access.Context{})
if got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
}
})
}
}
// TestCanaryGrantValidates pins that the canary grant passes the domain's
// structural check and the engine's schema validation, so it can be installed
// through the policy store.
func TestCanaryGrantValidates(t *testing.T) {
grant := access.CanaryGrantPolicy(org.DefaultOrgID, "canary-svc")
forbid := access.CanaryGrantForbidPolicy(org.DefaultOrgID, "canary-svc")
for _, p := range []access.Policy{grant, forbid} {
if err := p.Validate(); err != nil {
t.Fatalf("Validate %s: %v", p.ID, err)
}
}
engine := New([]access.Policy{grant, forbid})
for _, p := range []access.Policy{grant, forbid} {
if err := engine.Validate(p); err != nil {
t.Fatalf("engine Validate %s: %v", p.ID, err)
}
}
if len(engine.Problems()) != 0 {
t.Fatalf("problems = %v, want none", engine.Problems())
}
}
@@ -52,3 +52,13 @@ func DefaultUpdateStateDir() string {
}
return filepath.Join(dir, InstanceName(), "update")
}
// UpdateStateDir is the one resolution of the host's update state directory:
// ARCHIE_UPDATE_STATE_DIR when set, else the default. The daemon's
// transactions and the dashboard's update snapshot must read the same one.
func UpdateStateDir() string {
if dir := os.Getenv("ARCHIE_UPDATE_STATE_DIR"); dir != "" {
return dir
}
return DefaultUpdateStateDir()
}
@@ -195,6 +195,16 @@ func (f *Forge) Comment(ctx context.Context, owner, repo string, number int, bod
return resp.GetId(), err
}
func (f *Forge) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) {
resp, err := call(ctx, f, "create issue", func(c forgev1.ForgeServiceClient) (*forgev1.CreateIssueResponse, error) {
return c.CreateIssue(ctx, &forgev1.CreateIssueRequest{Repo: ref(owner, repo), Title: title, Body: body, Labels: labels})
})
if err != nil {
return 0, err
}
return int(resp.GetNumber()), nil
}
func (f *Forge) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
_, err := call(ctx, f, "close issue", func(c forgev1.ForgeServiceClient) (*forgev1.CloseIssueResponse, error) {
return c.CloseIssue(ctx, &forgev1.CloseIssueRequest{Repo: ref(owner, repo), Number: int32(number), Comment: comment}) // issue numbers fit int32
@@ -0,0 +1,123 @@
// Package issuerpc lets the Gateway's curators list and file issues through
// the daemon, which alone holds forge credentials.
package issuerpc
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"time"
"github.com/nats-io/nats.go"
"github.com/samcharles93/archie-core/internal/forge"
"github.com/samcharles93/archie-core/internal/natsrpc"
)
const (
listSubject = "archie.gateway.issue-list"
createSubject = "archie.gateway.issue-create"
)
type request struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
Title string `json:"title,omitempty"`
Body string `json:"body,omitempty"`
Labels []string `json:"labels,omitempty"`
}
type listResponse struct {
natsrpc.Envelope
Issues []forge.Issue `json:"issues,omitempty"`
}
type createResponse struct {
natsrpc.Envelope
Number int `json:"number,omitempty"`
}
// Server is the daemon side. Forge returns the instance forge, or nil while
// none is configured; Allowed refuses a repository the instance does not manage.
type Server struct {
Forge func() forge.IssueForge
Allowed func(ctx context.Context, owner, repo string) error
Log *slog.Logger
}
func (s *Server) forge(ctx context.Context, req request) (forge.IssueForge, error) {
if err := s.Allowed(ctx, req.Owner, req.Repo); err != nil {
return nil, err
}
f := s.Forge()
if f == nil {
return nil, errors.New("forge is not configured")
}
return f, nil
}
// Register serves the issue subjects on nc.
func (s *Server) Register(nc *nats.Conn) (func(), error) {
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
{Subject: listSubject, Handler: func(ctx context.Context, msg *nats.Msg) {
var req request
if err := json.Unmarshal(msg.Data, &req); err != nil {
natsrpc.Respond(msg, s.Log, "issuerpc", listResponse{Envelope: natsrpc.NewEnvelope(err)})
return
}
f, err := s.forge(ctx, req)
var issues []forge.Issue
if err == nil {
issues, err = f.IssuesWithLabel(ctx, req.Owner, req.Repo, "")
}
natsrpc.Respond(msg, s.Log, "issuerpc", listResponse{Envelope: natsrpc.NewEnvelope(err), Issues: issues})
}},
{Subject: createSubject, Handler: func(ctx context.Context, msg *nats.Msg) {
var req request
if err := json.Unmarshal(msg.Data, &req); err != nil {
natsrpc.Respond(msg, s.Log, "issuerpc", createResponse{Envelope: natsrpc.NewEnvelope(err)})
return
}
f, err := s.forge(ctx, req)
var number int
if err == nil {
number, err = f.CreateIssue(ctx, req.Owner, req.Repo, req.Title, req.Body, req.Labels)
}
natsrpc.Respond(msg, s.Log, "issuerpc", createResponse{Envelope: natsrpc.NewEnvelope(err), Number: number})
}},
})
}
// Client is the Gateway side.
type Client struct {
Conn *nats.Conn
Timeout time.Duration
}
func (c Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} }
// OpenIssues lists every open issue (not PR) of owner/repo.
func (c Client) OpenIssues(ctx context.Context, owner, repo string) ([]forge.Issue, error) {
resp, err := natsrpc.Call[listResponse](ctx, c.rpc(), listSubject, request{Owner: owner, Repo: repo})
if err != nil {
return nil, err
}
if err := resp.Err(); err != nil {
return nil, fmt.Errorf("list issues: %w", err)
}
return resp.Issues, nil
}
// CreateIssue files an issue and returns its number.
func (c Client) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) {
resp, err := natsrpc.Call[createResponse](ctx, c.rpc(), createSubject, request{Owner: owner, Repo: repo, Title: title, Body: body, Labels: labels})
if err != nil {
return 0, err
}
if err := resp.Err(); err != nil {
return 0, fmt.Errorf("create issue: %w", err)
}
return resp.Number, nil
}
+7 -2
View File
@@ -31,11 +31,16 @@ import (
// the tool_calls transcript the composition projection writes through.
var (
_ storecontract.CaptureStore = (*EDA)(nil)
_ storecontract.CaptureRefusalStore = (*EDA)(nil)
_ storecontract.MappingStore = (*EDA)(nil)
_ storecontract.BindingStore = (*EDA)(nil)
_ storecontract.BindingDispatcher = (*EDA)(nil)
_ storecontract.MappingMatchRecorder = (*EDA)(nil)
_ storecontract.EventTypeStore = (*EDA)(nil)
_ storecontract.BindingStore = (*EDA)(nil)
_ storecontract.SourceStore = (*EDA)(nil)
_ storecontract.DispatchLedger = (*EDA)(nil)
_ storecontract.BindingDispatcher = (*EDA)(nil)
_ storecontract.PlaybookDispatcher = (*EDA)(nil)
_ storecontract.HarnessSecretStore = (*EDA)(nil)
)
// EDA is the PostgreSQL-backed EDA persistence.
@@ -14,8 +14,6 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
var _ storecontract.EventTypeStore = (*EDA)(nil)
func eventTypeValue(r postgresdb.EventType) (eventtype.EventType, error) {
t := eventtype.EventType{
ID: r.ID, Source: r.Source, Name: r.Name, WorkspaceID: org.WorkspaceID(r.WorkspaceID),
@@ -15,8 +15,6 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
var _ storecontract.HarnessSecretStore = (*EDA)(nil)
// harnessSecretPayload is the JSON shape sealed into harness_secrets.secret_enc:
// the whole token set behind one envelope, never separate plaintext columns.
type harnessSecretPayload struct {
@@ -11,8 +11,6 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
var _ storecontract.RunCredentialStore = (*Store)(nil)
func (s *Store) PutRunCredential(ctx context.Context, digest [32]byte, taskID int64, expires time.Time) error {
return s.queries().InsertRunCredential(ctx, postgresdb.InsertRunCredentialParams{Digest: digest[:], TaskID: taskID, ExpiresAt: expires})
}
@@ -13,8 +13,6 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
var _ storecontract.SourceStore = (*EDA)(nil)
// InsertSource stores a new source in one of the acting org's workspaces,
// its default one when src names none; a workspace the org does not have is
// ErrInvalidWorkspace. The path is the primary key, so a taken path is
+11
View File
@@ -134,9 +134,20 @@ func taskFromRow(t postgresdb.Task) *workflow.Task {
// Compile-time checks: *Store satisfies every surface the SQLite store did.
var (
_ storecontract.TaskStore = (*Store)(nil)
_ storecontract.TaskLifecycle = (*Store)(nil)
_ storecontract.TaskParker = (*Store)(nil)
_ storecontract.TaskQueries = (*Store)(nil)
_ storecontract.TaskEvents = (*Store)(nil)
_ storecontract.TaskArchiver = (*Store)(nil)
_ storecontract.TaskRetryer = (*Store)(nil)
_ storecontract.ReviewGateResponder = (*Store)(nil)
_ storecontract.RemediationStarter = (*Store)(nil)
_ storecontract.OutcomePoster = (*Store)(nil)
_ storecontract.StepRecorder = (*Store)(nil)
_ storecontract.StepReader = (*Store)(nil)
_ storecontract.ExecutionCanceller = (*Store)(nil)
_ storecontract.BindingTaskCreator = (*Store)(nil)
_ storecontract.RunCredentialStore = (*Store)(nil)
_ storecontract.ConfigSnapshotStore = (*Store)(nil)
_ storecontract.ChannelStatusStore = (*Store)(nil)
_ storecontract.ApplyStatusStore = (*Store)(nil)
@@ -111,6 +111,18 @@ var (
_ storecontract.PresenceStore = (*Client)(nil)
_ storecontract.CaptureRefusalStore = (*Client)(nil)
_ storecontract.ExecutionCanceller = (*Client)(nil)
_ storecontract.TaskLifecycle = (*Client)(nil)
_ storecontract.TaskParker = (*Client)(nil)
_ storecontract.TaskQueries = (*Client)(nil)
_ storecontract.TaskEvents = (*Client)(nil)
_ storecontract.TaskArchiver = (*Client)(nil)
_ storecontract.TaskRetryer = (*Client)(nil)
_ storecontract.ReviewGateResponder = (*Client)(nil)
_ storecontract.RemediationStarter = (*Client)(nil)
_ storecontract.OutcomePoster = (*Client)(nil)
_ storecontract.StepReader = (*Client)(nil)
_ storecontract.DispatchLedger = (*Client)(nil)
_ storecontract.EventTypeStore = (*Client)(nil)
_ identity.Repository = (*Client)(nil)
_ storepkg.Installations = (*Client)(nil)
_ identity.PersonalTokens = (*Client)(nil)
@@ -90,6 +90,40 @@ func (s *accountServer) RevokePersonalToken(ctx context.Context, r *pb.RevokePer
return &pb.RevokePersonalTokenResponse{}, nil
}
// BindIdentityPersonalToken binds a token to a named non-user identity, the
// credential a service account acts with. The audit actor is the caller's
// principal, so the request never names who did it.
func (s *accountServer) BindIdentityPersonalToken(ctx context.Context, r *pb.BindIdentityPersonalTokenRequest) (*pb.BindIdentityPersonalTokenResponse, error) {
if s.deps.PersonalTokens == nil {
return nil, status.Error(codes.Unavailable, "personal tokens unavailable")
}
if s.deps.Identities == nil {
return nil, status.Error(codes.Unavailable, "identity store unavailable")
}
caller, ok := access.PrincipalFromContext(ctx)
if !ok || caller.IdentityID == "" {
return nil, status.Error(codes.Unauthenticated, "binding an identity token requires a principal")
}
target, err := s.deps.Identities.Get(ctx, identity.IdentityID(r.GetIdentityId()))
if err != nil {
return nil, s.identityStatus(ctx, err)
}
if target.Kind == identity.KindUser {
return nil, s.identityStatus(ctx, fmt.Errorf("%w: personal tokens belong to a signed-in person", identity.ErrInvalid))
}
if !target.CanAct() {
return nil, s.identityStatus(ctx, fmt.Errorf("%w: identity is not active", identity.ErrIllegalTransition))
}
subject, err := tokenSubject(r.GetId())
if err != nil {
return nil, err
}
if err := s.deps.PersonalTokens.BindPersonalToken(ctx, target.ID, subject, r.GetName(), optionalTime(r.GetExpiresAt()), tokenAudit(ctx, caller.IdentityID, "bind", r.GetId())); err != nil {
return nil, s.identityStatus(ctx, err)
}
return &pb.BindIdentityPersonalTokenResponse{}, nil
}
func (c *Client) AddPersonalToken(ctx context.Context, subject identity.Subject, name string, expiresAt *time.Time) error {
_, err := c.account.AddPersonalToken(ctx, &pb.AddPersonalTokenRequest{Id: subject.Subject, Name: name, ExpiresAt: optionalTimestamp(expiresAt)})
return identityClientError(err)
@@ -115,6 +149,15 @@ func (c *Client) RevokePersonalToken(ctx context.Context, id string) error {
return identityClientError(err)
}
// BindPersonalToken binds a token to a named identity rather than the caller's
// principal. The audit argument is accepted for the caller-side contract but
// never sent: the store attributes the bind to the caller's own principal, so
// a request cannot claim an actor.
func (c *Client) BindPersonalToken(ctx context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, _ identity.Audit) error {
_, err := c.account.BindIdentityPersonalToken(ctx, &pb.BindIdentityPersonalTokenRequest{IdentityId: string(id), Id: subject.Subject, Name: name, ExpiresAt: optionalTimestamp(expiresAt)})
return identityClientError(err)
}
func optionalTimestamp(t *time.Time) *timestamppb.Timestamp {
if t == nil {
return nil
@@ -6,6 +6,10 @@ import (
"testing"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
@@ -49,3 +53,88 @@ func TestPersonalTokenOwner(t *testing.T) {
})
}
}
type bindCalls struct {
identity.PersonalTokenStore
bound bool
id identity.IdentityID
subject identity.Subject
name string
expires *time.Time
audit identity.Audit
}
func (b *bindCalls) BindPersonalToken(_ context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, audit identity.Audit) error {
b.bound, b.id, b.subject, b.name, b.expires, b.audit = true, id, subject, name, expiresAt, audit
return nil
}
type bindIdentityRepo struct {
identity.Repository
values map[identity.IdentityID]identity.Identity
}
func (r bindIdentityRepo) Get(_ context.Context, id identity.IdentityID) (identity.Identity, error) {
if value, ok := r.values[id]; ok {
return value, nil
}
return identity.Identity{}, identity.ErrNotFound
}
// TestBindIdentityPersonalToken pins the named-identity bind: a service
// account gets the token with the caller as audit actor, while a user target,
// an unknown or inactive identity, a malformed token id and a caller with no
// principal are all refused without binding.
func TestBindIdentityPersonalToken(t *testing.T) {
id := strings.Repeat("ab", 32)
sa := identity.Identity{ID: "sa1", Kind: identity.KindServiceAccount, DisplayName: "Canary", Lifecycle: identity.LifecycleActive}
user := identity.Identity{ID: "u1", Kind: identity.KindUser, DisplayName: "Alice", Lifecycle: identity.LifecycleActive}
suspended := identity.Identity{ID: "sa2", Kind: identity.KindBot, DisplayName: "Old", Lifecycle: identity.LifecycleSuspended}
repo := bindIdentityRepo{values: map[identity.IdentityID]identity.Identity{sa.ID: sa, user.ID: user, suspended.ID: suspended}}
tests := []struct {
name string
target identity.IdentityID
tokenID string
noPrincipal bool
wantCode codes.Code
wantBound bool
}{
{"service account binds with the caller as actor", sa.ID, id, false, codes.OK, true},
{"user target is refused", user.ID, id, false, codes.FailedPrecondition, false},
{"unknown identity is refused", "nope", id, false, codes.NotFound, false},
{"inactive identity is refused", suspended.ID, id, false, codes.FailedPrecondition, false},
{"malformed token id is refused", sa.ID, "not-hex", false, codes.FailedPrecondition, false},
{"no principal is refused", sa.ID, id, true, codes.Unauthenticated, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
store := &bindCalls{}
s := &accountServer{server: &server{deps: Deps{PersonalTokens: store, Identities: repo}}}
ctx := context.Background()
if !tt.noPrincipal {
ctx = access.WithPrincipal(ctx, access.Principal{IdentityID: "alice"})
}
expires := time.Now().UTC().Add(30 * 24 * time.Hour).Truncate(time.Second)
_, err := s.BindIdentityPersonalToken(ctx, &pb.BindIdentityPersonalTokenRequest{IdentityId: string(tt.target), Id: tt.tokenID, Name: "ci", ExpiresAt: timestamppb.New(expires)})
if got := status.Code(err); got != tt.wantCode {
t.Fatalf("code=%v want=%v err=%v", got, tt.wantCode, err)
}
if store.bound != tt.wantBound {
t.Fatalf("bound=%v want=%v", store.bound, tt.wantBound)
}
if !tt.wantBound {
return
}
wantSubject := identity.Subject{Issuer: identity.PersonalTokenIssuer, Subject: id}
if store.id != sa.ID || store.name != "ci" || store.subject != wantSubject {
t.Fatalf("bind id=%q name=%q subject=%+v, want %q %q %+v", store.id, store.name, store.subject, sa.ID, "ci", wantSubject)
}
if store.expires == nil || !store.expires.Equal(expires) {
t.Fatalf("expires=%v want %v", store.expires, expires)
}
if store.audit.ActorID != "alice" || store.audit.RequestID != "personal-token:bind:"+id {
t.Fatalf("audit=%+v, want actor alice request personal-token:bind:<id>", store.audit)
}
})
}
}
+37 -23
View File
@@ -6,14 +6,17 @@ import (
)
// The canary host installs each release from the next channel. Its behaviour
// in the 24 hours after a release is compared with its own behaviour in the
// 24 hours before, because there's only one production host to compare with.
// in the window after a release was installed is compared with its own
// behaviour in the window before, because there's only one production host to
// compare with.
const (
// CanaryWindow is how long a release runs on the canary before it can be
// promoted. A day covers one full cycle of schedules and traffic.
// CanaryWindow is the default window a release runs on the canary before
// it can be promoted. A day covers one full cycle of schedules and
// traffic.
CanaryWindow = 24 * time.Hour
// canarySettle is how long the install and restart get, counted from when
// the release was issued, before any check can fail the release.
// the release was installed on the canary, before any check can fail the
// release.
canarySettle = 30 * time.Minute
// minFinished is the fewest finished tasks needed to judge the park rate.
minFinished = 5
@@ -47,7 +50,7 @@ type CanarySignals struct {
Installed string
Ready bool
// NewActionAlerts are open action-severity alerts first raised since
// the release was issued.
// the release was installed.
NewActionAlerts []string
Baseline CanaryWindowSignals
Canary CanaryWindowSignals
@@ -59,11 +62,20 @@ type CanaryVerdict struct {
Reasons []string
}
// JudgeCanary decides what to do with a release, given how long ago it was
// issued. Once the release has settled, a failed hard check rolls it back at
// any time. Error and park rates are compared with the baseline only after the
// full window has passed.
func JudgeCanary(version string, elapsed time.Duration, s CanarySignals) CanaryVerdict {
// JudgeCanaryNow decides from the current signals alone, for an operator
// promoting without waiting out the window: the settle and window waits are
// skipped by construction, every hard and relative check still applies.
func JudgeCanaryNow(version string, now time.Time, window time.Duration, s CanarySignals) CanaryVerdict {
return JudgeCanary(version, now.Add(-(window + canarySettle)), now, window, s)
}
// JudgeCanary decides what to do with a release, given when it was installed
// on the canary host. Once the release has settled, a failed hard check rolls
// it back at any time. Error and park rates are judged against the baseline
// whenever both windows carry enough data, so a breach rolls the release back
// even mid-window; a full window with no failure promotes it.
func JudgeCanary(version string, installedAt, now time.Time, window time.Duration, s CanarySignals) CanaryVerdict {
elapsed := now.Sub(installedAt)
if elapsed < canarySettle {
return CanaryVerdict{Decision: CanaryWait, Reasons: []string{"settling after install"}}
}
@@ -80,11 +92,8 @@ func JudgeCanary(version string, elapsed time.Duration, s CanarySignals) CanaryV
if len(failed) > 0 {
return CanaryVerdict{Decision: CanaryRollBack, Reasons: failed}
}
if elapsed < CanaryWindow {
return CanaryVerdict{Decision: CanaryWait, Reasons: []string{fmt.Sprintf("%s of %s elapsed", elapsed.Round(time.Minute), CanaryWindow)}}
}
var notes []string
if reason, ok := judgeErrors(s.Baseline, s.Canary); !ok {
if reason, ok := judgeErrors(s.Baseline, s.Canary, window); !ok {
failed = append(failed, reason)
} else {
notes = append(notes, reason)
@@ -97,32 +106,37 @@ func JudgeCanary(version string, elapsed time.Duration, s CanarySignals) CanaryV
if len(failed) > 0 {
return CanaryVerdict{Decision: CanaryRollBack, Reasons: failed}
}
if elapsed < window {
reasons := append([]string{fmt.Sprintf("%s of %s elapsed since the install", elapsed.Round(time.Minute), window)}, notes...)
return CanaryVerdict{Decision: CanaryWait, Reasons: reasons}
}
return CanaryVerdict{Decision: CanaryPromote, Reasons: notes}
}
// judgeErrors fails when the canary logged more than twice the baseline's
// error lines plus ten. Each count is scaled up to a full day when the log
// error lines plus ten. Each count is scaled up to a full window when the log
// covers only part of its window.
func judgeErrors(baseline, canary CanaryWindowSignals) (string, bool) {
func judgeErrors(baseline, canary CanaryWindowSignals, window time.Duration) (string, bool) {
if baseline.Covered < minLogCoverage || canary.Covered <= 0 {
return "error log doesn't reach back over the baseline; error signal skipped", true
}
scale := func(w CanaryWindowSignals) float64 {
return float64(w.Errors) * float64(CanaryWindow) / float64(w.Covered)
return float64(w.Errors) * float64(window) / float64(w.Covered)
}
before, after := scale(baseline), scale(canary)
limit := 2*before + 10
if after > limit {
return fmt.Sprintf("%.0f error log lines per day against a limit of %.0f (baseline %.0f)", after, limit, before), false
return fmt.Sprintf("%.0f error log lines per window against a limit of %.0f (baseline %.0f)", after, limit, before), false
}
return fmt.Sprintf("%.0f error log lines per day, limit %.0f", after, limit), true
return fmt.Sprintf("%.0f error log lines per window, limit %.0f", after, limit), true
}
// judgeParks fails when the share of finished tasks that parked or died rose
// more than ten points over the baseline.
// more than ten points over the baseline. Both windows need the minimum
// finished tasks before the rates are compared.
func judgeParks(baseline, canary CanaryWindowSignals) (string, bool) {
if canary.Finished < minFinished {
return fmt.Sprintf("%d finished tasks, fewer than %d; park signal skipped", canary.Finished, minFinished), true
if canary.Finished < minFinished || baseline.Finished < minFinished {
return fmt.Sprintf("%d finished tasks on the canary and %d in the baseline, fewer than %d each; park signal skipped", canary.Finished, baseline.Finished, minFinished), true
}
rate := func(w CanaryWindowSignals) float64 {
if w.Finished == 0 {
+29 -26
View File
@@ -32,44 +32,47 @@ var (
const updateSettingsPath = "/api/control-plane/resources/update-settings"
// Signals reads the canary's current state. Tasks and error lines are split
// into the day before the release was issued and the time since.
func (d CanaryDashboard) Signals(ctx context.Context, issued, now time.Time) (CanarySignals, error) {
// into the window before the release was installed on the canary and the time
// since.
func (d CanaryDashboard) Signals(ctx context.Context, installedAt, now time.Time, window time.Duration) (CanarySignals, error) {
var s CanarySignals
var err error
if s.Installed, _, err = d.installed(ctx); err != nil {
if s.Installed, _, _, err = d.Installed(ctx); err != nil {
return s, err
}
if s.Ready, err = d.ready(ctx); err != nil {
return s, err
}
if s.NewActionAlerts, err = d.actionAlerts(ctx, issued); err != nil {
if s.NewActionAlerts, err = d.actionAlerts(ctx, installedAt); err != nil {
return s, err
}
if err := d.tasks(ctx, issued, &s); err != nil {
if err := d.tasks(ctx, installedAt, window, &s); err != nil {
return s, err
}
return s, d.errors(ctx, issued, now, &s)
return s, d.errors(ctx, installedAt, now, window, &s)
}
// installed returns the daemon version the canary runs, and the raw update
// snapshot it offers, which an install request must send back unchanged.
func (d CanaryDashboard) installed(ctx context.Context) (string, json.RawMessage, error) {
// Installed returns the daemon version the canary runs, when that release was
// installed on the canary host (zero when the host doesn't report it), and
// the raw update snapshot it offers, which an install request must send back
// unchanged.
func (d CanaryDashboard) Installed(ctx context.Context) (version string, installedAt time.Time, snapshot json.RawMessage, err error) {
var body struct {
Snapshot json.RawMessage `json:"snapshot"`
}
if _, err := d.call(ctx, http.MethodGet, "/api/chat/update", nil, &body); err != nil {
return "", nil, err
return "", time.Time{}, nil, err
}
var snapshot Snapshot
if err := json.Unmarshal(body.Snapshot, &snapshot); err != nil {
return "", nil, fmt.Errorf("decode update snapshot: %w", err)
var snap Snapshot
if err := json.Unmarshal(body.Snapshot, &snap); err != nil {
return "", time.Time{}, nil, fmt.Errorf("decode update snapshot: %w", err)
}
for _, c := range snapshot.Components {
for _, c := range snap.Components {
if c.ID == "daemon" {
return c.Installed, body.Snapshot, nil
return c.Installed, snap.InstalledAt, body.Snapshot, nil
}
}
return "", body.Snapshot, errors.New("canary reports no daemon version")
return "", time.Time{}, body.Snapshot, errors.New("canary reports no daemon version")
}
func (d CanaryDashboard) ready(ctx context.Context) (bool, error) {
@@ -104,8 +107,8 @@ func (d CanaryDashboard) actionAlerts(ctx context.Context, since time.Time) ([]s
// tasks reads tasks, newest update first, until it reaches tasks older than
// the baseline window.
func (d CanaryDashboard) tasks(ctx context.Context, issued time.Time, s *CanarySignals) error {
from := issued.Add(-CanaryWindow)
func (d CanaryDashboard) tasks(ctx context.Context, at time.Time, window time.Duration, s *CanarySignals) error {
from := at.Add(-window)
cursor := ""
for range 50 {
var page []struct {
@@ -125,7 +128,7 @@ func (d CanaryDashboard) tasks(ctx context.Context, issued time.Time, s *CanaryS
continue
}
w := &s.Canary
if t.UpdatedAt.Before(issued) {
if t.UpdatedAt.Before(at) {
w = &s.Baseline
}
w.Finished++
@@ -144,7 +147,7 @@ func (d CanaryDashboard) tasks(ctx context.Context, issued time.Time, s *CanaryS
// errors counts error-level lines in each window. A log read returns a
// limited number of lines, so a truncated read only reaches back as far as
// its oldest line.
func (d CanaryDashboard) errors(ctx context.Context, issued, now time.Time, s *CanarySignals) error {
func (d CanaryDashboard) errors(ctx context.Context, at, now time.Time, window time.Duration, s *CanarySignals) error {
var body struct {
Entries []struct {
Time time.Time `json:"time"`
@@ -154,24 +157,24 @@ func (d CanaryDashboard) errors(ctx context.Context, issued, now time.Time, s *C
if _, err := d.call(ctx, http.MethodGet, "/api/logs?level=error&limit=2000", nil, &body); err != nil {
return err
}
from := issued.Add(-CanaryWindow)
from := at.Add(-window)
if body.Truncated {
from = now
if len(body.Entries) > 0 {
from = later(body.Entries[0].Time, issued.Add(-CanaryWindow))
from = later(body.Entries[0].Time, at.Add(-window))
}
}
for _, e := range body.Entries {
switch {
case e.Time.Before(from):
case e.Time.Before(issued):
case e.Time.Before(at):
s.Baseline.Errors++
default:
s.Canary.Errors++
}
}
s.Baseline.Covered = max(issued.Sub(from), 0)
s.Canary.Covered = now.Sub(later(from, issued))
s.Baseline.Covered = max(at.Sub(from), 0)
s.Canary.Covered = now.Sub(later(from, at))
return nil
}
@@ -232,7 +235,7 @@ func (d CanaryDashboard) Install(ctx context.Context, version string, wait time.
deadline := time.Now().Add(wait)
requested := false
for {
installed, snapshot, err := d.installed(ctx)
installed, _, snapshot, err := d.Installed(ctx)
switch {
case err != nil:
// The dashboard drops off while the install restarts it.
+51 -18
View File
@@ -5,10 +5,11 @@ import (
"time"
)
// A release promotes only after a full window with no hard failure and no
// relative signal past its threshold; any hard failure after settling rolls
// it back at once.
// A release promotes only after a full window counted from its install with
// no hard failure and no relative signal past its threshold; any failure after
// settling rolls it back at once, even mid-window.
func TestJudgeCanary(t *testing.T) {
installed := time.Date(2026, 1, 2, 12, 0, 0, 0, time.UTC)
healthy := func() CanarySignals {
return CanarySignals{
Installed: "1.1.0", Ready: true,
@@ -23,34 +24,66 @@ func TestJudgeCanary(t *testing.T) {
}
cases := []struct {
name string
elapsed time.Duration
elapsed time.Duration // now minus the install time
window time.Duration
signals CanarySignals
want CanaryDecision
}{
{"settling ignores a failed check", 10 * time.Minute, with(func(s *CanarySignals) { s.Ready = false }), CanaryWait},
{"healthy mid-window waits", 2 * time.Hour, healthy(), CanaryWait},
{"healthy at the window promotes", CanaryWindow, healthy(), CanaryPromote},
{"the watchdog rolled the install back", 2 * time.Hour, with(func(s *CanarySignals) { s.Installed = "1.0.0" }), CanaryRollBack},
{"readiness degraded", 2 * time.Hour, with(func(s *CanarySignals) { s.Ready = false }), CanaryRollBack},
{"a new action alert", 2 * time.Hour, with(func(s *CanarySignals) { s.NewActionAlerts = []string{"queue stalled"} }), CanaryRollBack},
{"errors past twice the baseline plus ten", CanaryWindow, with(func(s *CanarySignals) { s.Canary.Errors = 31 }), CanaryRollBack},
{"errors at the limit", CanaryWindow, with(func(s *CanarySignals) { s.Canary.Errors = 30 }), CanaryPromote},
{"errors scaled from a partly covered log", CanaryWindow, with(func(s *CanarySignals) {
{"settling counts from the install", 10 * time.Minute, CanaryWindow, with(func(s *CanarySignals) { s.Ready = false }), CanaryWait},
{"healthy mid-window waits", 2 * time.Hour, CanaryWindow, healthy(), CanaryWait},
{"healthy at the window promotes", CanaryWindow, CanaryWindow, healthy(), CanaryPromote},
{"healthy at a custom window promotes", 12 * time.Hour, 12 * time.Hour, healthy(), CanaryPromote},
{"the watchdog rolled the install back", 2 * time.Hour, CanaryWindow, with(func(s *CanarySignals) { s.Installed = "1.0.0" }), CanaryRollBack},
{"readiness degraded", 2 * time.Hour, CanaryWindow, with(func(s *CanarySignals) { s.Ready = false }), CanaryRollBack},
{"a new action alert", 2 * time.Hour, CanaryWindow, with(func(s *CanarySignals) { s.NewActionAlerts = []string{"queue stalled"} }), CanaryRollBack},
{"errors past twice the baseline plus ten", CanaryWindow, CanaryWindow, with(func(s *CanarySignals) { s.Canary.Errors = 31 }), CanaryRollBack},
{"errors at the limit", CanaryWindow, CanaryWindow, with(func(s *CanarySignals) { s.Canary.Errors = 30 }), CanaryPromote},
{"errors scaled from a partly covered log", CanaryWindow, CanaryWindow, with(func(s *CanarySignals) {
s.Canary.Errors, s.Canary.Covered = 8, 6*time.Hour
}), CanaryRollBack},
{"a baseline the log doesn't reach skips errors", CanaryWindow, with(func(s *CanarySignals) {
{"a baseline the log doesn't reach skips errors", CanaryWindow, CanaryWindow, with(func(s *CanarySignals) {
s.Baseline.Covered, s.Canary.Errors = 30*time.Minute, 500
}), CanaryPromote},
{"park rate up more than ten points", CanaryWindow, with(func(s *CanarySignals) { s.Canary.Bad = 5 }), CanaryRollBack},
{"park rate up ten points", CanaryWindow, with(func(s *CanarySignals) { s.Canary.Bad = 4 }), CanaryPromote},
{"too few tasks skips the park rate", CanaryWindow, with(func(s *CanarySignals) { s.Canary = CanaryWindowSignals{Finished: 4, Bad: 4, Covered: CanaryWindow} }), CanaryPromote},
{"a mid-window error breach rolls back early", 2 * time.Hour, CanaryWindow, with(func(s *CanarySignals) { s.Canary.Errors = 31 }), CanaryRollBack},
{"park rate up more than ten points", CanaryWindow, CanaryWindow, with(func(s *CanarySignals) { s.Canary.Bad = 5 }), CanaryRollBack},
{"park rate up ten points", CanaryWindow, CanaryWindow, with(func(s *CanarySignals) { s.Canary.Bad = 4 }), CanaryPromote},
{"too few canary tasks skips the park rate", CanaryWindow, CanaryWindow, with(func(s *CanarySignals) { s.Canary = CanaryWindowSignals{Finished: 4, Bad: 4, Covered: CanaryWindow} }), CanaryPromote},
{"a thin baseline skips the park rate", CanaryWindow, CanaryWindow, with(func(s *CanarySignals) {
s.Baseline.Finished, s.Baseline.Bad = 2, 0
s.Canary.Bad = 5
}), CanaryPromote},
{"a mid-window park breach rolls back early", 2 * time.Hour, CanaryWindow, with(func(s *CanarySignals) { s.Canary.Bad = 5 }), CanaryRollBack},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := JudgeCanary("1.1.0", tc.elapsed, tc.signals)
got := JudgeCanary("1.1.0", installed, installed.Add(tc.elapsed), tc.window, tc.signals)
if got.Decision != tc.want {
t.Fatalf("decision = %s, want %s (%v)", got.Decision, tc.want, got.Reasons)
}
})
}
}
// Judging "now" skips the settle and window waits but still applies every
// hard and relative check.
func TestJudgeCanaryNow(t *testing.T) {
healthy := CanarySignals{
Installed: "1.1.0", Ready: true,
Baseline: CanaryWindowSignals{Finished: 20, Bad: 2, Errors: 10, Covered: CanaryWindow},
Canary: CanaryWindowSignals{Finished: 20, Bad: 2, Errors: 12, Covered: CanaryWindow},
}
now := time.Date(2026, 1, 2, 12, 10, 0, 0, time.UTC)
if got := JudgeCanaryNow("1.1.0", now, CanaryWindow, healthy); got.Decision != CanaryPromote {
t.Fatalf("healthy now = %s, want promote (%v)", got.Decision, got.Reasons)
}
degraded := healthy
degraded.Ready = false
if got := JudgeCanaryNow("1.1.0", now, CanaryWindow, degraded); got.Decision != CanaryRollBack {
t.Fatalf("degraded now = %s, want roll back (%v)", got.Decision, got.Reasons)
}
breached := healthy
breached.Canary.Bad = 10
if got := JudgeCanaryNow("1.1.0", now, CanaryWindow, breached); got.Decision != CanaryRollBack {
t.Fatalf("park breach now = %s, want roll back (%v)", got.Decision, got.Reasons)
}
}
+47
View File
@@ -0,0 +1,47 @@
package releaseupdate
import (
"context"
"fmt"
digest "github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"oras.land/oras-go/v2/registry"
"github.com/samcharles93/archie-core/internal/domain/distribution"
)
// Installable reports whether a release can still be installed from source:
// the zip blob its statement names must be present in the release repository
// and the agent image it pins must still resolve. A canary must never be
// pinned to a release whose artifacts are gone, or it would be stranded on a
// version it can never install again.
func Installable(ctx context.Context, source distribution.Source, release Release) error {
zipDigest, err := digest.Parse(release.Statement.Zip.Digest)
if err != nil {
return fmt.Errorf("zip digest %q: %w", release.Statement.Zip.Digest, err)
}
repo, err := pushRepository(source.Reference)
if err != nil {
return err
}
exists, err := repo.Exists(ctx, ocispec.Descriptor{Digest: zipDigest})
if err != nil {
return fmt.Errorf("resolve zip blob %s in %s: %w", release.Statement.Zip.Digest, source.Reference, err)
}
if !exists {
return fmt.Errorf("zip blob %s (%s) is absent from %s", release.Statement.Zip.Digest, release.Statement.Zip.Name, source.Reference)
}
image, err := registry.ParseReference(release.Statement.AgentImage)
if err != nil {
return fmt.Errorf("agent image %q: %w", release.Statement.AgentImage, err)
}
imageRepo, err := pushRepository(image.Registry + "/" + image.Repository)
if err != nil {
return err
}
if _, err := imageRepo.Resolve(ctx, image.Reference); err != nil {
return fmt.Errorf("agent image %s: %w", release.Statement.AgentImage, err)
}
return nil
}
+3
View File
@@ -44,6 +44,9 @@ type Component struct {
type Snapshot struct {
Components []Component
Deferred bool
// InstalledAt is when the installed release was committed on this host,
// from its installed.json. Zero when the host doesn't record one.
InstalledAt time.Time `json:"installed_at"`
}
func (s Snapshot) Available() []Component {
+54
View File
@@ -40,6 +40,7 @@ const (
journalDir = "transaction"
journalFile = "journal.json"
snapshotFile = "db.pre-update.dump"
installedFile = "installed.json"
lockWait = 60 * time.Second
)
@@ -126,6 +127,39 @@ type journal struct {
// JournalPath is where an unfinished transaction lives.
func JournalPath(stateDir string) string { return filepath.Join(stateDir, journalDir) }
// installedRecord is the host's durable note of which release it last
// committed (or rolled back to) and when, so a canary can count its window
// from the actual install rather than the release statement.
type installedRecord struct {
Version string `json:"version"`
CommittedAt time.Time `json:"committed_at"`
}
// recordInstall writes installed.json atomically: the file is the source of
// truth for when the running release was installed.
func recordInstall(stateDir, version string, at time.Time) error {
data, err := json.Marshal(installedRecord{Version: version, CommittedAt: at.UTC()})
if err != nil {
return err
}
return fsutil.WriteFileAtomic(filepath.Join(stateDir, installedFile), data, 0o600)
}
// LastInstall reads the host's installed record. ok is false when the file is
// missing or malformed, as on a host that updated before install times were
// recorded.
func LastInstall(stateDir string) (version string, at time.Time, ok bool) {
data, err := os.ReadFile(filepath.Join(stateDir, installedFile))
if err != nil {
return "", time.Time{}, false
}
var record installedRecord
if err := json.Unmarshal(data, &record); err != nil || record.Version == "" || record.CommittedAt.IsZero() {
return "", time.Time{}, false
}
return record.Version, record.CommittedAt, true
}
// Run drives the transaction in the journal to an outcome. recovering is set
// on boot: it never waits for the lock, and a transaction that was prepared
// but never started is abandoned rather than started unattended.
@@ -158,6 +192,17 @@ func (t *Transaction) Run(ctx context.Context, recovering bool) error {
if err := t.startUnits(ctx, j, ""); err != nil {
return err
}
// A crash between the outcome phase and recordInstall must not lose
// the install record, so the recovery path writes it too.
version := j.Version
if j.Phase == phaseRolledBack {
version = j.Previous[ComponentDaemon]
}
if version != "" {
if err := recordInstall(t.StateDir, version, time.Now().UTC()); err != nil {
return err
}
}
return t.remove()
default:
return t.rollback(ctx, j)
@@ -182,6 +227,9 @@ func (t *Transaction) promote(ctx context.Context, j journal) error {
if err := t.setPhase(&j, phaseCommitted); err != nil {
return err
}
if err := recordInstall(t.StateDir, j.Version, time.Now().UTC()); err != nil {
return fmt.Errorf("record the install: %w", err)
}
return t.remove()
}
@@ -252,6 +300,12 @@ func (t *Transaction) rollback(ctx context.Context, j journal) error {
if err := t.setPhase(&j, phaseRolledBack); err != nil {
return t.incomplete(err)
}
// The host is back on the previous release; installed.json follows it.
if version := j.Previous[ComponentDaemon]; version != "" {
if err := recordInstall(t.StateDir, version, time.Now().UTC()); err != nil {
return t.incomplete(err)
}
}
if err := t.startUnits(ctx, j, started); err != nil {
return t.incomplete(err)
}
@@ -21,6 +21,7 @@ import (
digest "github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/samcharles93/archie-core/internal/buildinfo"
"github.com/samcharles93/archie-core/internal/domain/distribution"
"github.com/samcharles93/archie-core/internal/infrastructure/signedoci"
)
@@ -146,6 +147,11 @@ func TestTransaction(t *testing.T) {
// the env file beside its config; pin both to this test's own files so
// the result never depends on the machine's real archie config.
t.Setenv(DatabasePasswordEnv, "test-password")
// Stamp this binary as a release, as a host installed from one is, so the
// journal's previous daemon version is a real version.
stamped := buildinfo.Version
buildinfo.Version = "1.0.0"
defer func() { buildinfo.Version = stamped }()
configPath := filepath.Join(t.TempDir(), "config.toml")
if err := os.WriteFile(configPath, []byte("database_url = \"postgres://archie@/archie?host=/tmp/archie-test\"\n"), 0o600); err != nil {
t.Fatal(err)
@@ -257,10 +263,51 @@ func TestTransaction(t *testing.T) {
found && (got.HealthCheck != tt.want.report || got.RolledBack != (tt.want.report == "failed") || got.RestoredDatabase != tt.want.restoredDatabase) {
t.Errorf("report = %+v (found %v), want %+v", got, found, tt.want)
}
// A transaction that ran to an outcome records which release the
// host now runs and when it was installed.
if tt.prepare == "" && tt.crashAt == "" {
if version, at, ok := LastInstall(tx.StateDir); !ok || version != tt.want.version || at.IsZero() {
t.Errorf("installed.json after the transaction = %q, %v, %v; want %s", version, at, ok, tt.want.version)
}
}
})
}
}
// installed.json is the host's durable record of which release it last
// committed or rolled back to, and when.
func TestLastInstall(t *testing.T) {
dir := t.TempDir()
if _, _, ok := LastInstall(dir); ok {
t.Fatal("a missing installed.json reports ok")
}
at := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
if err := recordInstall(dir, "1.2.3", at); err != nil {
t.Fatal(err)
}
var raw map[string]any
data, err := os.ReadFile(filepath.Join(dir, installedFile))
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(data, &raw); err != nil {
t.Fatalf("installed.json is not JSON: %v", err)
}
if raw["version"] != "1.2.3" || raw["committed_at"] != "2026-01-02T03:04:05Z" {
t.Fatalf("installed.json = %v, want version 1.2.3 and committed_at 2026-01-02T03:04:05Z", raw)
}
version, got, ok := LastInstall(dir)
if !ok || version != "1.2.3" || !got.Equal(at) {
t.Fatalf("LastInstall = %q, %v, %v; want 1.2.3, %v, true", version, got, ok, at)
}
if err := os.WriteFile(filepath.Join(dir, installedFile), []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
if _, _, ok := LastInstall(dir); ok {
t.Fatal("a malformed installed.json reports ok")
}
}
// releaseHandler serves one release's zip and SHA256SUMS the way GitHub
// release downloads are laid out.
func releaseHandler(t *testing.T, candidate string, corrupt bool) (http.Handler, ed25519.PublicKey) {
@@ -13,8 +13,8 @@ const defaultDenialsListLimit = 100
// first. The route's read_audit grant limits it to the org's admins and
// owners, and the store scopes the list by the credential's org, so no
// request field chooses the org an operator reads.
func (s *Server) handleListDenials(w http.ResponseWriter, r *http.Request) {
if s.DenialLister == nil {
func (a *accessAPI) handleListDenials(w http.ResponseWriter, r *http.Request) {
if a.denials == nil {
http.Error(w, "denial records unavailable", http.StatusServiceUnavailable)
return
}
@@ -22,7 +22,7 @@ func (s *Server) handleListDenials(w http.ResponseWriter, r *http.Request) {
if err != nil || limit <= 0 || limit > 1000 {
limit = defaultDenialsListLimit
}
denials, err := s.DenialLister.ListDenials(r.Context(), policyOrg(r), int(limit))
denials, err := a.denials.ListDenials(r.Context(), policyOrg(r), int(limit))
if err != nil {
writeControlPlaneError(w, err)
return
@@ -95,7 +95,7 @@ func TestHandleListDenialsScopesToCallersOrg(t *testing.T) {
ctx := org.WithOrg(access.WithPrincipal(t.Context(), principal), tt.caller)
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/access/denials"+tt.query, nil)
rec := httptest.NewRecorder()
srv.handleListDenials(rec, req)
newAccessAPI(srv).handleListDenials(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 body=%s", rec.Code, rec.Body.String())
}
@@ -129,7 +129,7 @@ func TestHandleListDenialsUnwired(t *testing.T) {
srv := &Server{}
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/access/denials", nil)
rec := httptest.NewRecorder()
srv.handleListDenials(rec, req)
newAccessAPI(srv).handleListDenials(rec, req)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", rec.Code)
}
@@ -9,6 +9,24 @@ import (
"github.com/samcharles93/archie-core/internal/domain/org"
)
// accessAPI owns the /api/access routes: the stored policy chain and the
// recorded denials. Either store may be nil; its routes then answer 503.
type accessAPI struct {
policies access.PolicyStore
denials access.DenialStore
}
func newAccessAPI(s *Server) *accessAPI {
return &accessAPI{policies: s.Policies, denials: s.DenialLister}
}
func (a *accessAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/access/policies", a.handleListPolicies)
mux.HandleFunc("PUT /api/access/policies", a.handlePutPolicy)
mux.HandleFunc("DELETE /api/access/policies", a.handleDeletePolicy)
mux.HandleFunc("GET /api/access/denials", a.handleListDenials)
}
// policyOrg is the org a policy request acts in: the caller's.
func policyOrg(r *http.Request) org.OrgID {
if principal, ok := access.PrincipalFromContext(r.Context()); ok {
@@ -19,12 +37,12 @@ func policyOrg(r *http.Request) org.OrgID {
// handleListPolicies lists the caller's org policies, and the instance
// policies when the caller is the instance owner.
func (s *Server) handleListPolicies(w http.ResponseWriter, r *http.Request) {
if s.Policies == nil {
func (a *accessAPI) handleListPolicies(w http.ResponseWriter, r *http.Request) {
if a.policies == nil {
http.Error(w, "policies unavailable", http.StatusServiceUnavailable)
return
}
policies, err := s.Policies.ListPolicies(r.Context())
policies, err := a.policies.ListPolicies(r.Context())
if err != nil {
writeControlPlaneError(w, err)
return
@@ -39,12 +57,12 @@ func (s *Server) handleListPolicies(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{"policies": out, "shipped": shippedPolicyIDs()})
}
func (s *Server) handlePutPolicy(w http.ResponseWriter, r *http.Request) {
p, ok := s.decodePolicy(w, r)
func (a *accessAPI) handlePutPolicy(w http.ResponseWriter, r *http.Request) {
p, ok := a.decodePolicy(w, r)
if !ok {
return
}
version, err := s.Policies.PutPolicy(r.Context(), p)
version, err := a.policies.PutPolicy(r.Context(), p)
if err != nil {
writePolicyError(w, err)
return
@@ -52,12 +70,12 @@ func (s *Server) handlePutPolicy(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]int64{"version": version})
}
func (s *Server) handleDeletePolicy(w http.ResponseWriter, r *http.Request) {
p, ok := s.decodePolicy(w, r)
func (a *accessAPI) handleDeletePolicy(w http.ResponseWriter, r *http.Request) {
p, ok := a.decodePolicy(w, r)
if !ok {
return
}
if err := s.Policies.DeletePolicy(r.Context(), p); err != nil {
if err := a.policies.DeletePolicy(r.Context(), p); err != nil {
writePolicyError(w, err)
return
}
@@ -66,8 +84,8 @@ func (s *Server) handleDeletePolicy(w http.ResponseWriter, r *http.Request) {
// decodePolicy reads a policy and pins it to the caller's org: no request
// field chooses the org, and instance policies are not edited here.
func (s *Server) decodePolicy(w http.ResponseWriter, r *http.Request) (access.Policy, bool) {
if s.Policies == nil {
func (a *accessAPI) decodePolicy(w http.ResponseWriter, r *http.Request) (access.Policy, bool) {
if a.policies == nil {
http.Error(w, "policies unavailable", http.StatusServiceUnavailable)
return access.Policy{}, false
}
+18 -1
View File
@@ -58,8 +58,12 @@ func (s *Server) accountIdentity(r *http.Request) (identity.Identity, error) {
func (s *Server) requireAccount(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Any active identity may authenticate: a person, or a service
// account whose bearer token carries a scoped grant. What the
// identity may then do is the policy chain's call, not the
// credential kind's; an inactive identity is refused here.
value, err := s.accountIdentity(r)
if err != nil || value.Kind != identity.KindUser || !value.CanAct() {
if err != nil || !value.CanAct() {
if err == nil {
err = identity.ErrCredentialRejected
}
@@ -413,3 +417,16 @@ func (s *Server) authenticateBrowser(ctx context.Context, credential string) (id
}
return verify(ctx, credential)
}
func (s *Server) memberIssuer(r *http.Request) string {
if store, ok := s.authenticationSettings(); ok {
value, err := store.AuthenticationSettings(r.Context())
if err != nil {
return ""
}
if value.PublicURL != "" {
return value.OIDCIssuer
}
}
return s.Issuer
}
+144
View File
@@ -2,6 +2,7 @@ package webui
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
@@ -131,6 +132,149 @@ func TestAccountSessionFailureIsClosed(t *testing.T) {
}
}
// TestRequireAccountAdmitsAnyActiveIdentity pins the bearer-token gate: any
// active identity -- a person or a service account -- is admitted and rides
// the context as the acting identity, while an inactive one is refused, so a
// scoped service-account token can use the API without being a user.
func TestRequireAccountAdmitsAnyActiveIdentity(t *testing.T) {
tests := []struct {
name string
value identity.Identity
want int
}{
{"active user", identity.Identity{ID: "u1", Kind: identity.KindUser, DisplayName: "User", Lifecycle: identity.LifecycleActive}, http.StatusOK},
{"active service account", identity.Identity{ID: "sa1", Kind: identity.KindServiceAccount, DisplayName: "Canary", Lifecycle: identity.LifecycleActive}, http.StatusOK},
{"active bot", identity.Identity{ID: "b1", Kind: identity.KindBot, DisplayName: "Bot", Lifecycle: identity.LifecycleActive}, http.StatusOK},
{"suspended user", identity.Identity{ID: "u2", Kind: identity.KindUser, DisplayName: "User", Lifecycle: identity.LifecycleSuspended}, http.StatusUnauthorized},
{"retired service account", identity.Identity{ID: "sa2", Kind: identity.KindServiceAccount, DisplayName: "Canary", Lifecycle: identity.LifecycleRetired}, http.StatusUnauthorized},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := &Server{
Authenticate: func(context.Context, string) (identity.Identity, error) { return tt.value, nil },
}
var acting identity.IdentityID
handler := srv.requireAccount(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
if value, ok := ActingIdentity(r.Context()); ok {
acting = value.ID
}
}))
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "https://archie.example/api/summary", nil)
req.Header.Set("Authorization", "Bearer archie_pat_test")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != tt.want {
t.Fatalf("status=%d want=%d body=%s", rec.Code, tt.want, rec.Body.String())
}
if tt.want == http.StatusOK && acting != tt.value.ID {
t.Fatalf("acting identity = %q, want %q", acting, tt.value.ID)
}
})
}
}
// identityRepo answers Get for the identities a test names.
type identityRepo struct {
identity.Repository
values map[identity.IdentityID]identity.Identity
}
func (s identityRepo) Get(_ context.Context, id identity.IdentityID) (identity.Identity, error) {
value, ok := s.values[id]
if !ok {
return identity.Identity{}, identity.ErrNotFound
}
return value, nil
}
// identityTokenStore carries both token contracts: the remote caller's view
// (embedded) and the store side, whose BindPersonalToken names an identity.
type identityTokenStore struct {
identity.PersonalTokens
bound bool
id identity.IdentityID
subject identity.Subject
name string
}
func (s *identityTokenStore) BindPersonalToken(_ context.Context, id identity.IdentityID, subject identity.Subject, name string, _ *time.Time, _ identity.Audit) error {
s.bound, s.id, s.subject, s.name = true, id, subject, name
return nil
}
func (s *identityTokenStore) SubjectsOf(context.Context, identity.IdentityID, string) ([]identity.PersonalToken, error) {
return nil, nil
}
func (s *identityTokenStore) UnbindSubject(context.Context, identity.IdentityID, identity.Subject, identity.Audit) error {
return nil
}
func (s *identityTokenStore) PersonalTokenOf(context.Context, identity.Subject) (identity.PersonalToken, error) {
return identity.PersonalToken{}, identity.ErrNotFound
}
func (s *identityTokenStore) TouchPersonalToken(context.Context, identity.Subject, time.Time) error {
return nil
}
// TestIdentityTokenCreate pins the per-identity token route: an active
// service account gets its raw token exactly once and the store binds only
// its hash, while an unknown or inactive identity is refused.
func TestIdentityTokenCreate(t *testing.T) {
active := identity.Identity{ID: "sa1", Kind: identity.KindServiceAccount, DisplayName: "Canary", Lifecycle: identity.LifecycleActive}
suspended := identity.Identity{ID: "sa2", Kind: identity.KindServiceAccount, DisplayName: "Old", Lifecycle: identity.LifecycleSuspended}
tests := []struct {
name, id, body string
want int
}{
{"active service account", "sa1", `{"name":"ci","days":30}`, http.StatusCreated},
{"unknown identity", "nope", `{"name":"ci","days":30}`, http.StatusBadRequest},
{"inactive identity", "sa2", `{"name":"ci","days":30}`, http.StatusConflict},
{"bad name", "sa1", `{"name":" ","days":30}`, http.StatusBadRequest},
{"bad lifetime", "sa1", `{"name":"ci","days":10}`, http.StatusBadRequest},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
store := &identityTokenStore{}
srv := &Server{
Identities: identityRepo{values: map[identity.IdentityID]identity.Identity{active.ID: active, suspended.ID: suspended}},
PersonalTokens: store,
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "https://archie.example/api/identities/"+tt.id+"/tokens", strings.NewReader(tt.body))
req.Header.Set("Content-Type", "application/json")
req.SetPathValue("id", tt.id)
rec := httptest.NewRecorder()
newIdentitiesAPI(srv).handleIdentityTokenCreate(rec, req)
if rec.Code != tt.want {
t.Fatalf("status=%d want=%d body=%s", rec.Code, tt.want, rec.Body.String())
}
if tt.want != http.StatusCreated {
if store.bound {
t.Fatal("a refused request still bound a token")
}
return
}
var body struct {
ID string `json:"id"`
Token string `json:"token"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response: %v (%s)", err, rec.Body.String())
}
if !strings.HasPrefix(body.Token, "archie_pat_") || body.ID == "" {
t.Fatalf("response must show the raw token once: %+v", body)
}
if !store.bound || store.id != active.ID || store.name != "ci" {
t.Fatalf("bound = %+v, want id %q name %q", store, active.ID, "ci")
}
if store.subject.Issuer != identity.PersonalTokenIssuer || store.subject.Subject != body.ID {
t.Fatalf("store kept subject %+v, want the token's hash %q under %q", store.subject, body.ID, identity.PersonalTokenIssuer)
}
})
}
}
type unavailableAccounts struct{ identity.Accounts }
func (unavailableAccounts) AccountSetupRequired(context.Context) (bool, error) {
@@ -3,6 +3,7 @@ package webui
import (
"context"
"errors"
"log/slog"
"net/http"
"strconv"
"strings"
@@ -72,10 +73,23 @@ func viewOfAlert(a alert.Alert) alertView {
return view
}
// alertsAPI owns the /api/alerts routes. A nil source answers 503.
type alertsAPI struct {
alerts AlertSource
log *slog.Logger
}
func newAlertsAPI(s *Server) *alertsAPI { return &alertsAPI{alerts: s.Alerts, log: s.Log} }
func (a *alertsAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/alerts", a.handleAlerts)
mux.HandleFunc("POST /api/alerts/{id}/dismiss", a.handleAlertDismiss)
}
// handleAlerts lists the caller's org's alerts: open ones unless ?state names
// others (comma separated), most severe first.
func (s *Server) handleAlerts(w http.ResponseWriter, r *http.Request) {
if s.Alerts == nil {
func (a *alertsAPI) handleAlerts(w http.ResponseWriter, r *http.Request) {
if a.alerts == nil {
http.Error(w, "alerts unavailable", http.StatusServiceUnavailable)
return
}
@@ -85,9 +99,9 @@ func (s *Server) handleAlerts(w http.ResponseWriter, r *http.Request) {
filter.States = append(filter.States, alert.State(strings.TrimSpace(state)))
}
}
alerts, err := s.Alerts.ListAlerts(r.Context(), policyOrg(r), filter)
alerts, err := a.alerts.ListAlerts(r.Context(), policyOrg(r), filter)
if err != nil {
s.Log.ErrorContext(r.Context(), "list alerts", "err", err)
a.log.ErrorContext(r.Context(), "list alerts", "err", err)
http.Error(w, "list alerts failed", http.StatusBadGateway)
return
}
@@ -99,8 +113,8 @@ func (s *Server) handleAlerts(w http.ResponseWriter, r *http.Request) {
}
// handleAlertDismiss dismisses one open alert of the caller's org.
func (s *Server) handleAlertDismiss(w http.ResponseWriter, r *http.Request) {
if s.Alerts == nil {
func (a *alertsAPI) handleAlertDismiss(w http.ResponseWriter, r *http.Request) {
if a.alerts == nil {
http.Error(w, "alerts unavailable", http.StatusServiceUnavailable)
return
}
@@ -109,12 +123,12 @@ func (s *Server) handleAlertDismiss(w http.ResponseWriter, r *http.Request) {
http.Error(w, "invalid alert id", http.StatusBadRequest)
return
}
err = s.Alerts.DismissAlert(r.Context(), policyOrg(r), id, access.ActorFromContext(r.Context()))
err = a.alerts.DismissAlert(r.Context(), policyOrg(r), id, access.ActorFromContext(r.Context()))
switch {
case errors.Is(err, alert.ErrNotFound):
http.Error(w, "alert not found", http.StatusNotFound)
case err != nil:
s.Log.ErrorContext(r.Context(), "dismiss alert", "err", err)
a.log.ErrorContext(r.Context(), "dismiss alert", "err", err)
http.Error(w, "dismiss alert failed", http.StatusBadGateway)
default:
w.WriteHeader(http.StatusNoContent)
+2 -337
View File
@@ -1,159 +1,14 @@
package webui
import (
"context"
"errors"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
// bindingRequest is the wire shape POST /api/bindings and
// PATCH /api/bindings/{id} both accept. ID/Version/Status/CreatedAt/UpdatedAt
// are server-assigned (or server-driven), never taken from the request body.
type bindingRequest struct {
Name string `json:"name"`
Matcher binding.Matcher `json:"matcher"`
MappingID string `json:"mapping_id"`
Filter string `json:"filter"`
Workflow string `json:"workflow"`
// Owner and Repo optionally pin the binding to one configured repo,
// for multi-repo deployments. Both empty is valid (falls back to the
// daemon's single-configured-repo behaviour); binding.Validate
// rejects setting only one.
Owner string `json:"owner"`
Repo string `json:"repo"`
// RepoParam takes the repository from a mapped parameter instead.
RepoParam string `json:"repo_param"`
Inputs map[string]binding.InputSource `json:"inputs"`
}
// bindingView is a listed binding with its source's signing state, so the
// list can flag a binding that dispatches unsigned events.
type bindingView struct {
binding.Binding
Unsigned bool `json:"unsigned"`
// WorkflowDisabled marks a binding whose org has disabled the workflow it
// targets; it does not dispatch until the workflow is enabled again.
WorkflowDisabled bool `json:"workflow_disabled"`
// LastOutcome is the binding's newest ledger row: the task it started or
// the reason it started none.
LastOutcome *storecontract.Dispatch `json:"last_outcome,omitempty"`
}
func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
bindings, err := s.Bindings.ListBindings(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list bindings", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
unsigned, err := s.unsignedSources(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list sources", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
enablement, _, err := s.workflowEnablement(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "workflow enablement", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
views := make([]bindingView, 0, len(bindings))
for _, b := range bindings {
if !listedIn(r, b.WorkspaceID) {
continue
}
views = append(views, bindingView{
Binding: b, Unsigned: unsigned[b.Matcher.Source], WorkflowDisabled: !enablement.Enabled(b.OrgID, b.Workflow),
LastOutcome: s.lastOutcome(r.Context(), b.ID),
})
}
writeJSON(w, map[string]any{"bindings": views})
}
// lastOutcome returns a binding's newest dispatch, or nil when it has none or
// the ledger is unreadable.
func (s *Server) lastOutcome(ctx context.Context, bindingID string) *storecontract.Dispatch {
if s.Dispatches == nil {
return nil
}
rows, err := s.Dispatches.ListDispatches(ctx, storecontract.DispatchFilter{BindingID: bindingID, Limit: 1})
if err != nil {
s.Log.WarnContext(ctx, "binding last outcome", "binding", bindingID, "err", err)
return nil
}
if len(rows) == 0 {
return nil
}
return &rows[0]
}
func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
req, ok := decodeBody[bindingRequest](w, r)
if !ok {
return
}
b, ok := s.checkedBinding(w, r, "", req)
if !ok {
return
}
id, err := s.Bindings.InsertBinding(r.Context(), b)
if err != nil {
s.Log.ErrorContext(r.Context(), "insert binding", "err", err)
http.Error(w, "create binding failed", http.StatusInternalServerError)
return
}
created, err := s.Bindings.GetBinding(r.Context(), id)
if err != nil || created == nil {
s.Log.ErrorContext(r.Context(), "get binding after insert", "err", err, "id", id)
http.Error(w, "create binding failed", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, created)
}
func (s *Server) handleBindingGet(w http.ResponseWriter, r *http.Request) {
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
b, err := s.Bindings.GetBinding(r.Context(), id)
if err != nil {
s.Log.ErrorContext(r.Context(), "get binding", "err", err, "id", id)
http.Error(w, "get binding failed", http.StatusInternalServerError)
return
}
if b == nil {
http.Error(w, "binding not found", http.StatusNotFound)
return
}
writeJSON(w, b)
}
// handleDispatches serves the newest dispatch ledger rows for the resource the
// path names, linking bindings, captures and tasks to each other.
// path names, linking bindings, captures and tasks to each other. Shared by
// the bindings module and the captures/tasks routes, so it stays on Server.
func (s *Server) handleDispatches(filterFor func(id string) (storecontract.DispatchFilter, bool)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if s.Dispatches == nil {
@@ -175,193 +30,3 @@ func (s *Server) handleDispatches(filterFor func(id string) (storecontract.Dispa
writeJSON(w, dispatches)
}
}
func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
req, ok := decodeBody[bindingRequest](w, r)
if !ok {
return
}
b, ok := s.checkedBinding(w, r, id, req)
if !ok {
return
}
if err := s.Bindings.UpdateBinding(r.Context(), b); err != nil {
switch {
case errors.Is(err, storecontract.ErrBindingNotFound):
http.Error(w, "binding not found", http.StatusNotFound)
default:
s.Log.ErrorContext(r.Context(), "update binding", "err", err, "id", id)
http.Error(w, "update binding failed", http.StatusInternalServerError)
}
return
}
updated, err := s.Bindings.GetBinding(r.Context(), id)
if err != nil || updated == nil {
s.Log.ErrorContext(r.Context(), "get binding after update", "err", err, "id", id)
http.Error(w, "update binding failed", http.StatusInternalServerError)
return
}
writeJSON(w, updated)
}
func (s *Server) handleBindingDelete(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
if err := s.Bindings.DeleteBinding(r.Context(), id); err != nil {
if errors.Is(err, storecontract.ErrBindingNotFound) {
http.Error(w, "binding not found", http.StatusNotFound)
return
}
s.Log.ErrorContext(r.Context(), "delete binding", "err", err, "id", id)
http.Error(w, "delete binding failed", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleBindingTransition serves one binding lifecycle command (approve,
// pause, resume) and answers the binding as it now stands.
func (s *Server) handleBindingTransition(verb string, apply func(storecontract.BindingStore, context.Context, string) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Bindings == nil {
http.Error(w, "bindings not configured", http.StatusServiceUnavailable)
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
if err := apply(s.Bindings, r.Context(), id); err != nil {
switch {
case errors.Is(err, storecontract.ErrBindingNotFound):
http.Error(w, "binding not found", http.StatusNotFound)
case errors.Is(err, storecontract.ErrBindingTransition):
http.Error(w, "binding cannot "+verb+" from its current state", http.StatusConflict)
default:
s.Log.ErrorContext(r.Context(), verb+" binding", "err", err, "id", id)
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
}
return
}
updated, err := s.Bindings.GetBinding(r.Context(), id)
if err != nil || updated == nil {
s.Log.ErrorContext(r.Context(), "get binding after "+verb, "err", err, "id", id)
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
return
}
writeJSON(w, updated)
}
}
// checkedBinding builds the binding a create or update request describes and
// refuses it, having written the error, unless it is well-formed, its mapping
// exists, its filter compiles against the mapping's parameters, and its inputs
// and repository satisfy the workflow it targets.
func (s *Server) checkedBinding(w http.ResponseWriter, r *http.Request, id string, req bindingRequest) (binding.Binding, bool) {
b := binding.Binding{
ID: id,
Name: req.Name,
Matcher: req.Matcher,
MappingID: req.MappingID,
Filter: req.Filter,
Workflow: req.Workflow,
Owner: req.Owner,
Repo: req.Repo,
RepoParam: req.RepoParam,
Inputs: req.Inputs,
Status: binding.StatusPendingApproval,
}
if err := b.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
entry, found, err := s.workflowEntry(r.Context(), req.Workflow)
if err != nil {
http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
if !found {
http.Error(w, "binding: workflow not found: "+req.Workflow, http.StatusBadRequest)
return binding.Binding{}, false
}
enabled, err := s.bindingWorkflowEnabled(r.Context(), id, req.Workflow)
if err != nil {
http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
if !enabled {
http.Error(w, "binding: workflow is disabled: "+req.Workflow, http.StatusConflict)
return binding.Binding{}, false
}
iface, err := task.ParseWorkflowInterface(entry.YAML)
if err != nil {
http.Error(w, "binding: workflow "+req.Workflow+": "+err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
if s.Mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
m, err := s.Mappings.GetMapping(r.Context(), b.MappingID)
if err != nil {
s.Log.ErrorContext(r.Context(), "get mapping for binding", "err", err, "mapping", b.MappingID)
http.Error(w, "get mapping failed", http.StatusInternalServerError)
return binding.Binding{}, false
}
if m == nil {
http.Error(w, "binding: mapping not found: "+b.MappingID, http.StatusBadRequest)
return binding.Binding{}, false
}
if _, err := binding.CompileFilter(b.Filter, m.Fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
if err := b.CheckWorkflow(iface, m.Fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
return b, true
}
// bindingWorkflowEnabled reports whether the org owning binding id (the
// default org for a binding not yet created) has workflow enabled.
func (s *Server) bindingWorkflowEnabled(ctx context.Context, id, workflow string) (bool, error) {
owner := org.DefaultOrgID
if id != "" {
existing, err := s.Bindings.GetBinding(ctx, id)
if err != nil {
return false, err
}
if existing != nil {
owner = existing.OrgID
}
}
enablement, _, err := s.workflowEnablement(ctx)
return enablement.Enabled(owner, workflow), err
}
-122
View File
@@ -1,122 +0,0 @@
package webui
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"net/http"
"strings"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
type identityRequest struct {
DisplayName string `json:"display_name"`
Kind identity.Kind `json:"kind"`
ExpectedVersion int64 `json:"expected_version"`
}
func (s *Server) handleIdentitiesList(w http.ResponseWriter, r *http.Request) {
if s.Identities == nil {
http.Error(w, "identity store unavailable", http.StatusServiceUnavailable)
return
}
values, err := s.Identities.List(r.Context())
if err != nil {
writeIdentityError(w, err)
return
}
if values == nil {
values = []identity.Identity{}
}
writeJSON(w, map[string]any{"identities": values})
}
func (s *Server) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
request, ok := decodeBody[identityRequest](w, r)
if !ok {
return
}
id, err := randomIdentityID()
if err != nil {
http.Error(w, "cannot create identity ID", http.StatusInternalServerError)
return
}
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
value, err := identity.New(id, request.Kind, request.DisplayName)
if err == nil {
value, err = s.Identities.Create(r.Context(), value, audit)
}
if err != nil {
writeIdentityError(w, err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, value)
}
func (s *Server) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
request, ok := decodeBody[identityRequest](w, r)
if !ok {
return
}
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
command := identity.Command{Type: identity.CommandType(r.PathValue("command")), DisplayName: request.DisplayName}
value, err := s.Identities.Apply(r.Context(), identity.IdentityID(r.PathValue("id")), request.ExpectedVersion, command, audit)
if err != nil {
writeIdentityError(w, err)
return
}
writeJSON(w, value)
}
// webAudit attributes a dashboard write to the request's own principal: the
// person the dashboard acts as. Only a request with no principal at all falls
// back to the System identity, which is a real identity the repository
// resolves, never a name the request could claim for itself.
func webAudit(ctx context.Context) (identity.Audit, error) {
id, err := newControlPlaneRequestID()
if err != nil {
return identity.Audit{}, err
}
actor := identity.SystemID
if p, ok := access.PrincipalFromContext(ctx); ok && p.IdentityID != "" {
actor = p.IdentityID
}
return identity.Audit{ActorID: actor, Source: "archie-ui", RequestID: id}, nil
}
func randomIdentityID() (identity.IdentityID, error) {
var value [16]byte
if _, err := rand.Read(value[:]); err != nil {
return "", err
}
value[6] = value[6]&0x0f | 0x40
value[8] = value[8]&0x3f | 0x80
encoded := hex.EncodeToString(value[:])
return identity.IdentityID(encoded[:8] + "-" + encoded[8:12] + "-" + encoded[12:16] + "-" + encoded[16:20] + "-" + encoded[20:]), nil
}
func writeIdentityError(w http.ResponseWriter, err error) {
code := http.StatusInternalServerError
switch {
case errors.Is(err, identity.ErrNotFound):
code = http.StatusNotFound
case errors.Is(err, identity.ErrConflict), errors.Is(err, org.ErrLastOwner):
code = http.StatusConflict
case errors.Is(err, identity.ErrInvalid), errors.Is(err, identity.ErrIllegalTransition), errors.Is(err, identity.ErrSystemImmutable):
code = http.StatusBadRequest
}
http.Error(w, strings.TrimSpace(err.Error()), code)
}
+3 -236
View File
@@ -2,254 +2,21 @@ package webui
import (
"context"
"encoding/json"
"errors"
"net/http"
"slices"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// Shared source helpers: unsignedSources feeds the bindings list, recentRefusals
// the sources list, listedIn every workspace-scoped list.
// Capture sources and their signing setting. A secret is returned only by the
// two writes that generate it, so the operator can copy it into the sender;
// every other read withholds it. Turning signing off is a request plus an
// approval, both behind the same mutation gate that arms a binding.
func (s *Server) handleSourcesList(w http.ResponseWriter, r *http.Request) {
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
list, err := s.Sources.ListSources(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list sources", "err", err)
http.Error(w, "list sources failed", http.StatusInternalServerError)
return
}
list = slices.DeleteFunc(list, func(src source.Source) bool { return !listedIn(r, src.WorkspaceID) })
for i := range list {
list[i].Secret = ""
}
writeJSON(w, map[string]any{"sources": list, "refusals": s.recentRefusals(r)})
}
func (s *Server) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
var req struct {
Path string `json:"path"`
// Workspace is the caller's org workspace to create it in; empty is
// the default one.
Workspace org.WorkspaceID `json:"workspace"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
if !s.authorizeCreateIn(w, r, access.KindSource, req.Workspace) {
return
}
src, err := source.New(req.Path)
if errors.Is(err, source.ErrInvalidPath) || errors.Is(err, source.ErrReservedPath) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err == nil {
src.WorkspaceID = req.Workspace
err = s.Sources.InsertSource(r.Context(), src)
}
if err != nil {
s.sourceError(w, "create source", err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, src)
}
// handleSourceSigning turns signing on at once, or requests turning it off.
func (s *Server) handleSourceSigning(w http.ResponseWriter, r *http.Request) {
var req struct {
Signed bool `json:"signed"`
}
if !s.authorizeTaskMutation(w, r) {
return
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
transition := (*source.Source).RequestUnsigned
if req.Signed {
transition = (*source.Source).RequireSigning
}
s.transitionSource(w, r, transition)
}
func (s *Server) handleSourceApproveUnsigned(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
s.transitionSource(w, r, (*source.Source).ApproveUnsigned)
}
// transitionSource applies one domain signing transition and writes it with
// the state it was decided from, so a concurrent change is refused.
func (s *Server) transitionSource(w http.ResponseWriter, r *http.Request, transition func(*source.Source) error) {
src, ok := s.loadSource(w, r)
if !ok {
return
}
from := src.Signing
if err := transition(src); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return
}
if err := s.Sources.SetSourceSigning(r.Context(), src.Path, from, src.Signing); err != nil {
s.sourceError(w, "set source signing", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceSecret generates a new secret and returns it once.
func (s *Server) handleSourceSecret(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
src, ok := s.loadSource(w, r)
if !ok {
return
}
secret, err := source.NewSecret()
if err == nil {
err = s.Sources.SetSourceSecret(r.Context(), src.Path, secret)
}
if err != nil {
s.sourceError(w, "set source secret", err)
return
}
src.Secret = secret
writeJSON(w, src)
}
// handleSourceName relabels a source; its path does not change.
func (s *Server) handleSourceName(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
src, ok := s.loadSource(w, r)
if !ok {
return
}
var request struct {
Name string `json:"name"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
http.Error(w, "invalid source name", http.StatusBadRequest)
return
}
src.Name = strings.TrimSpace(request.Name)
if err := s.Sources.SetSourceName(r.Context(), src.Path, src.Name); err != nil {
s.sourceError(w, "set source name", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceDeliveryHeader sets the header that names a source's
// deliveries, so a sender's retry dispatches no second run.
func (s *Server) handleSourceDeliveryHeader(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
src, ok := s.loadSource(w, r)
if !ok {
return
}
var request struct {
Header string `json:"header"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
http.Error(w, "invalid delivery header", http.StatusBadRequest)
return
}
header, err := source.DeliveryHeader(request.Header)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
src.DeliveryHeader = header
if err := s.Sources.SetSourceDeliveryHeader(r.Context(), src.Path, header); err != nil {
s.sourceError(w, "set source delivery header", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceDelete deletes a source no armed binding fires on.
func (s *Server) handleSourceDelete(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
}
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
if err := s.Sources.DeleteSource(r.Context(), r.PathValue("path")); err != nil {
s.sourceError(w, "delete source", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) loadSource(w http.ResponseWriter, r *http.Request) (*source.Source, bool) {
if s.Sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return nil, false
}
src, err := s.Sources.GetSource(r.Context(), r.PathValue("path"))
if err != nil {
s.sourceError(w, "get source", err)
return nil, false
}
if src == nil {
http.Error(w, "source not found", http.StatusNotFound)
return nil, false
}
return src, true
}
func (s *Server) sourceError(w http.ResponseWriter, what string, err error) {
switch {
case errors.Is(err, storecontract.ErrSourcePathTaken):
http.Error(w, "source path already taken", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceSigningStale):
http.Error(w, "source signing changed; reload and retry", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceNotFound):
http.Error(w, "source not found", http.StatusNotFound)
case errors.Is(err, org.ErrInvalidWorkspace):
http.Error(w, "that workspace is not one of this org's", http.StatusBadRequest)
case errors.Is(err, storecontract.ErrSourceInUse):
http.Error(w, "an armed binding fires on this source; pause or delete it first", http.StatusConflict)
default:
s.Log.Error(what, "err", err)
http.Error(w, what+" failed", http.StatusInternalServerError)
}
}
// unsignedSources is the set of source paths approved to take unsigned
// events. With no source store nothing is unsigned.
func (s *Server) unsignedSources(ctx context.Context) (map[string]bool, error) {
@@ -7,12 +7,14 @@ import (
"errors"
"fmt"
"io"
"log/slog"
"maps"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"google.golang.org/grpc/codes"
@@ -21,6 +23,7 @@ import (
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/audit"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/ratelimit"
)
@@ -116,11 +119,46 @@ type auditResponse struct {
Facets *auditFacetsView `json:"facets,omitempty"`
}
// auditAPI owns the /api/audit routes. exporting admits one export per
// identity and exportRate bounds how many each identity starts an hour; an
// export is also bounded by its explicit range, a five-minute deadline and a
// page cap.
type auditAPI struct {
audit audit.Store
controlPlane controlpb.ControlPlaneServiceClient
log *slog.Logger
actorNames func(context.Context) func(string) string
workflowDefinitions func(context.Context) ([]task.Definition, error)
exportRate *ratelimit.Limiter
exportMu sync.Mutex
exporting map[string]bool
}
func newAuditAPI(s *Server) *auditAPI {
return &auditAPI{
audit: s.Audit,
controlPlane: s.ControlPlane,
log: s.Log,
actorNames: s.actorNames,
workflowDefinitions: newWorkflowsAPI(s).workflowDefinitions,
exportRate: ratelimit.New(auditExportWindow, auditExportPerHour),
exporting: map[string]bool{},
}
}
func (a *auditAPI) logf(msg string, args ...any) { warnf(a.log, msg, args...) }
func (a *auditAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/audit", a.handleAudit)
mux.HandleFunc("GET /api/audit/export", a.handleAuditExport)
}
// handleAudit is GET /api/audit: one page of the org-scoped feed. The org and
// the reader's authority come from the authenticated principal in the request
// context; the query string never names an org.
func (s *Server) handleAudit(w http.ResponseWriter, r *http.Request) {
if s.Audit == nil {
func (a *auditAPI) handleAudit(w http.ResponseWriter, r *http.Request) {
if a.audit == nil {
http.Error(w, "audit feed unavailable", http.StatusServiceUnavailable)
return
}
@@ -133,12 +171,12 @@ func (s *Server) handleAudit(w http.ResponseWriter, r *http.Request) {
http.Error(w, firstLine(err.Error()), http.StatusBadRequest)
return
}
page, err := s.Audit.ListAudit(r.Context(), filter, cursor, limit)
page, err := a.audit.ListAudit(r.Context(), filter, cursor, limit)
if err != nil {
writeAuditError(w, err)
return
}
labels, settings := s.auditLabels(r.Context())
labels, settings := a.auditLabels(r.Context())
records := make([]auditRecordView, 0, len(page.Entries))
for _, entry := range page.Entries {
records = append(records, auditRecord(entry, labels))
@@ -159,8 +197,8 @@ func (s *Server) handleAudit(w http.ResponseWriter, r *http.Request) {
// handleAuditExport is GET /api/audit/export?format=csv|json with the feed's
// filters. It requires an explicit range of at most a year and streams rows
// page by page.
func (s *Server) handleAuditExport(w http.ResponseWriter, r *http.Request) {
if s.Audit == nil {
func (a *auditAPI) handleAuditExport(w http.ResponseWriter, r *http.Request) {
if a.audit == nil {
http.Error(w, "audit feed unavailable", http.StatusServiceUnavailable)
return
}
@@ -185,12 +223,12 @@ func (s *Server) handleAuditExport(w http.ResponseWriter, r *http.Request) {
identity := auditExportIdentity(r.Context())
// Take the guard before charging the budget: a request rejected because
// the same identity is already exporting must cost no allowance.
if !s.beginAuditExport(identity) {
if !a.beginAuditExport(identity) {
http.Error(w, "an audit export is already running for this identity", http.StatusTooManyRequests)
return
}
defer s.endAuditExport(identity)
if !s.auditExportLimiter().Allow("audit-export", identity) {
defer a.endAuditExport(identity)
if !a.exportRate.Allow("audit-export", identity) {
http.Error(w, "too many audit exports; try again later", http.StatusTooManyRequests)
return
}
@@ -199,41 +237,41 @@ func (s *Server) handleAuditExport(w http.ResponseWriter, r *http.Request) {
// Count before any header is written: a match over the cap is the
// caller's problem to narrow, not a download that ends early.
if !s.auditExportWithinBudget(ctx, w, filter) {
if !a.auditExportWithinBudget(ctx, w, filter) {
return
}
// Fetch the first page before setting download headers: a failure here is
// still a normal error response, not a truncated file.
first, err := s.Audit.ListAudit(ctx, filter, audit.Cursor{}, auditExportPageSize)
first, err := a.audit.ListAudit(ctx, filter, audit.Cursor{}, auditExportPageSize)
if err != nil {
writeAuditError(w, err)
return
}
writeAuditExportHeaders(w, format)
labels, _ := s.auditLabels(ctx)
labels, _ := a.auditLabels(ctx)
flush := func() {}
if flusher, ok := w.(http.Flusher); ok {
flush = flusher.Flush
}
var rows int64
if format == "csv" {
rows, err = s.exportAuditCSV(ctx, filter, first, labels, w, flush)
rows, err = a.exportAuditCSV(ctx, filter, first, labels, w, flush)
} else {
rows, err = s.exportAuditJSON(ctx, filter, first, labels, w, flush)
rows, err = a.exportAuditJSON(ctx, filter, first, labels, w, flush)
}
if err != nil {
// Headers and status are already on the wire, so no error status is
// left to send. Abort the connection so the client sees a failed
// download rather than a silently short file.
s.logf("audit export failed", "format", format, "err", err)
a.logf("audit export failed", "format", format, "err", err)
panic(http.ErrAbortHandler)
}
// The file is complete; the trail row is bookkeeping, so a failed write
// is logged rather than turning a delivered export into a failed one.
if err := s.Audit.RecordAuditExport(r.Context(), format, filter.Hash(), rows); err != nil {
s.logf("record audit export", "format", format, "err", err)
if err := a.audit.RecordAuditExport(r.Context(), format, filter.Hash(), rows); err != nil {
a.logf("record audit export", "format", format, "err", err)
}
}
@@ -241,8 +279,8 @@ func (s *Server) handleAuditExport(w http.ResponseWriter, r *http.Request) {
// cap, answering before any header is written so the client never receives a
// truncated file it cannot tell from a complete one. A feed error is written
// with the same status mapping as a page read.
func (s *Server) auditExportWithinBudget(ctx context.Context, w http.ResponseWriter, filter audit.Filter) bool {
count, err := s.Audit.CountAudit(ctx, filter)
func (a *auditAPI) auditExportWithinBudget(ctx context.Context, w http.ResponseWriter, filter audit.Filter) bool {
count, err := a.audit.CountAudit(ctx, filter)
if err != nil {
writeAuditError(w, err)
return false
@@ -301,12 +339,12 @@ func writeAuditExportHeaders(w http.ResponseWriter, format string) {
w.Header().Set("X-Content-Type-Options", "nosniff")
}
func (s *Server) exportAuditCSV(ctx context.Context, filter audit.Filter, first audit.Page, labels *auditLabels, w io.Writer, flush func()) (int64, error) {
func (a *auditAPI) exportAuditCSV(ctx context.Context, filter audit.Filter, first audit.Page, labels *auditLabels, w io.Writer, flush func()) (int64, error) {
writer := csv.NewWriter(w)
if err := writer.Write(auditCSVHeader); err != nil {
return 0, err
}
rows, err := s.walkAudit(ctx, filter, first, func(entry audit.Entry) error {
rows, err := a.walkAudit(ctx, filter, first, func(entry audit.Entry) error {
return writer.Write(auditCSVRow(auditRecord(entry, labels)))
}, func() {
writer.Flush()
@@ -319,13 +357,13 @@ func (s *Server) exportAuditCSV(ctx context.Context, filter audit.Filter, first
return rows, err
}
func (s *Server) exportAuditJSON(ctx context.Context, filter audit.Filter, first audit.Page, labels *auditLabels, w io.Writer, flush func()) (int64, error) {
func (a *auditAPI) exportAuditJSON(ctx context.Context, filter audit.Filter, first audit.Page, labels *auditLabels, w io.Writer, flush func()) (int64, error) {
if _, err := io.WriteString(w, "["); err != nil {
return 0, err
}
encoder := json.NewEncoder(w)
firstRecord := true
rows, err := s.walkAudit(ctx, filter, first, func(entry audit.Entry) error {
rows, err := a.walkAudit(ctx, filter, first, func(entry audit.Entry) error {
if !firstRecord {
if _, err := io.WriteString(w, ","); err != nil {
return err
@@ -346,7 +384,7 @@ func (s *Server) exportAuditJSON(ctx context.Context, filter audit.Filter, first
// walkAudit streams every entry of the window in feed order and returns how
// many it emitted. It starts from the already-fetched first page so the caller
// could answer an error before any byte of the download was written.
func (s *Server) walkAudit(ctx context.Context, filter audit.Filter, first audit.Page, emit func(audit.Entry) error, afterPage func()) (int64, error) {
func (a *auditAPI) walkAudit(ctx context.Context, filter audit.Filter, first audit.Page, emit func(audit.Entry) error, afterPage func()) (int64, error) {
page := first
pages := 1
var rows int64
@@ -371,7 +409,7 @@ func (s *Server) walkAudit(ctx context.Context, filter audit.Filter, first audit
if !ok {
return rows, errAuditExportCursor
}
next, err := s.Audit.ListAudit(ctx, filter, cursor, auditExportPageSize)
next, err := a.audit.ListAudit(ctx, filter, cursor, auditExportPageSize)
if err != nil {
return rows, err
}
@@ -472,10 +510,10 @@ func (l *auditLabels) workflow(id string) string {
// auditLabels builds the label resolver and the settings-kind facet in one
// catalog read. A failed catalog read degrades labels to their ids; it never
// fails the feed.
func (s *Server) auditLabels(ctx context.Context) (*auditLabels, []auditSettingsKind) {
labels := &auditLabels{actorName: s.actorNames(ctx), titles: map[string]string{}}
func (a *auditAPI) auditLabels(ctx context.Context) (*auditLabels, []auditSettingsKind) {
labels := &auditLabels{actorName: a.actorNames(ctx), titles: map[string]string{}}
settings := []auditSettingsKind{}
for _, resource := range s.auditCatalogResources(ctx) {
for _, resource := range a.auditCatalogResources(ctx) {
if resource.GetTitle() != "" {
labels.titles[resource.GetKind()] = resource.GetTitle()
}
@@ -486,7 +524,7 @@ func (s *Server) auditLabels(ctx context.Context) (*auditLabels, []auditSettings
}
}
labels.workflowFn = func() map[string]string {
definitions, err := s.workflowDefinitions(ctx)
definitions, err := a.workflowDefinitions(ctx)
if err != nil {
return nil
}
@@ -502,11 +540,11 @@ func (s *Server) auditLabels(ctx context.Context) (*auditLabels, []auditSettings
// auditCatalogResources reads the control-plane catalogue once. A missing
// control plane or a failed read leaves labels at their ids rather than
// failing the feed.
func (s *Server) auditCatalogResources(ctx context.Context) []*controlpb.ResourceDescriptor {
if s.ControlPlane == nil {
func (a *auditAPI) auditCatalogResources(ctx context.Context) []*controlpb.ResourceDescriptor {
if a.controlPlane == nil {
return nil
}
catalog, err := s.ControlPlane.Catalog(ctx, &controlpb.CatalogRequest{})
catalog, err := a.controlPlane.Catalog(ctx, &controlpb.CatalogRequest{})
if err != nil {
return nil
}
@@ -639,33 +677,23 @@ func auditExportIdentity(ctx context.Context) string {
return "unknown"
}
func (s *Server) auditExportLimiter() *ratelimit.Limiter {
s.auditExportOnce.Do(func() {
s.auditExportRate = ratelimit.New(auditExportWindow, auditExportPerHour)
})
return s.auditExportRate
}
// beginAuditExport admits one export per identity. The guard is per identity,
// not process-wide: one person's long export must not stop another person in
// another org from taking their own.
func (s *Server) beginAuditExport(identity string) bool {
s.auditExportMu.Lock()
defer s.auditExportMu.Unlock()
if s.auditExporting == nil {
s.auditExporting = make(map[string]bool)
}
if s.auditExporting[identity] {
func (a *auditAPI) beginAuditExport(identity string) bool {
a.exportMu.Lock()
defer a.exportMu.Unlock()
if a.exporting[identity] {
return false
}
s.auditExporting[identity] = true
a.exporting[identity] = true
return true
}
func (s *Server) endAuditExport(identity string) {
s.auditExportMu.Lock()
delete(s.auditExporting, identity)
s.auditExportMu.Unlock()
func (a *auditAPI) endAuditExport(identity string) {
a.exportMu.Lock()
delete(a.exporting, identity)
a.exportMu.Unlock()
}
var auditCSVHeader = []string{
@@ -77,7 +77,7 @@ func TestAuditErrorMapping(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
srv := &Server{Audit: auditStub{err: tt.err}}
rec := httptest.NewRecorder()
srv.handleAudit(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit", nil))
newAuditAPI(srv).handleAudit(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit", nil))
if rec.Code != tt.want {
t.Fatalf("status = %d, want %d", rec.Code, tt.want)
}
@@ -90,7 +90,7 @@ func TestAuditErrorMapping(t *testing.T) {
func TestAuditUnavailableWithoutFeed(t *testing.T) {
rec := httptest.NewRecorder()
(&Server{}).handleAudit(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit", nil))
newAuditAPI(&Server{}).handleAudit(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit", nil))
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusServiceUnavailable)
}
@@ -104,7 +104,7 @@ func TestAuditExportRefusesOverTheRowCap(t *testing.T) {
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet,
"/api/audit/export?format=json&from=2026-01-01T00:00:00Z&to=2026-01-02T00:00:00Z", nil)
rec := httptest.NewRecorder()
srv.handleAuditExport(rec, req)
newAuditAPI(srv).handleAuditExport(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
}
+22 -5
View File
@@ -318,16 +318,17 @@ func routeOverride(r *http.Request, action access.Action, path string) (access.A
return actionManage(action), access.KindPolicy, segmentValue(path, 2), true
case matchPrefix(path, "/api/control-plane/resources"):
return controlPlaneResourceRoute(action, path)
case updateCommandRoute(action, path):
// Triggering or deferring an install changes the update object, not
// a workflow run: the dashboard kind carries the update's policy.
return access.ActionUpdate, access.KindDashboard, "update", true
case matchPrefix(path, "/api/chat"):
return chatRoute(action)
case matchSegment(path, "/api/sources/", "/secret"):
// Rotating a source's secret hands back its value.
return access.ActionReadSecret, access.KindSecret, segmentValue(path, 2), true
case matchPrefix(path, "/api/harness/terminal"):
// Opening the setup terminal updates the binding's secret.
return access.ActionUpdate, access.KindSecret, "", true
case matchPrefix(path, "/api/harness/bindings"):
return access.ActionRead, access.KindSecret, "", true
case matchPrefix(path, "/api/harness/terminal"), matchPrefix(path, "/api/harness/bindings"):
return harnessSecretRoute(path)
case matchPrefix(path, "/api/channels"), matchPrefix(path, "/api/config"),
matchPrefix(path, "/api/logs"), matchPrefix(path, "/api/tokens"):
return dashboardRoute(action, path)
@@ -335,6 +336,15 @@ func routeOverride(r *http.Request, action access.Action, path string) (access.A
return action, "", "", false
}
// harnessSecretRoute maps the harness surfaces, which work with the binding's
// secret: opening the setup terminal updates it, the bindings view reads it.
func harnessSecretRoute(path string) (access.Action, access.ResourceKind, string, bool) {
if matchPrefix(path, "/api/harness/terminal") {
return access.ActionUpdate, access.KindSecret, "", true
}
return access.ActionRead, access.KindSecret, "", true
}
// dashboardRoute maps the dashboard's own routes: channel settings are
// instance administration, while config, logs and a person's own tokens act
// only as that person, needing no more than a dashboard read.
@@ -395,6 +405,13 @@ func orgRouteAction(action access.Action, path string) access.Action {
return access.ActionUpdate
}
// updateCommandRoute reports whether the request is one of the chat update
// commands, which act on the update object rather than running a workflow.
func updateCommandRoute(action access.Action, path string) bool {
return action == access.ActionCreate &&
(path == "/api/chat/update/install" || path == "/api/chat/update/defer")
}
// chatRoute maps a chat request: posting runs a workflow, anything else reads
// the dashboard.
func chatRoute(action access.Action) (access.Action, access.ResourceKind, string, bool) {
+33 -4
View File
@@ -119,7 +119,7 @@ func TestSharedTokenOperatorPostsPersonalToken(t *testing.T) {
Principals: stubPrincipals(true),
PersonalTokens: tokens,
}
handler := s.requireToken(s.authorize(http.HandlerFunc(s.handlePersonalTokenCreate)))
handler := s.requireToken(s.authorize(http.HandlerFunc(newIdentitiesAPI(s).handlePersonalTokenCreate)))
rec := httptest.NewRecorder()
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/tokens", strings.NewReader(`{"name":"ci","days":30}`))
req.Header.Set("Authorization", "Bearer shared")
@@ -223,6 +223,35 @@ func TestChannelReloadRoute(t *testing.T) {
}
}
// TestChatRouteMapping pins the chat routes' actions: posting a message runs a
// workflow, while triggering or deferring an update changes the update object
// on the dashboard kind, so a scoped grant can carry it without any run right.
func TestChatRouteMapping(t *testing.T) {
tests := []struct {
method, path string
action access.Action
kind access.ResourceKind
id string
}{
{http.MethodPost, "/api/chat/update/install", access.ActionUpdate, access.KindDashboard, "update"},
{http.MethodPost, "/api/chat/update/defer", access.ActionUpdate, access.KindDashboard, "update"},
{http.MethodPost, "/api/chat/message", access.ActionRun, access.KindWorkflow, ""},
{http.MethodPost, "/api/chat/stream", access.ActionRun, access.KindWorkflow, ""},
{http.MethodPost, "/api/chat/cancel", access.ActionRun, access.KindWorkflow, ""},
{http.MethodPost, "/api/chat/answer", access.ActionRun, access.KindWorkflow, ""},
{http.MethodGet, "/api/chat/update", access.ActionRead, access.KindDashboard, ""},
{http.MethodGet, "/api/chat/sessions", access.ActionRead, access.KindDashboard, ""},
}
for _, tt := range tests {
t.Run(tt.method+" "+tt.path, func(t *testing.T) {
action, kind, id := accessRequest(httptest.NewRequestWithContext(t.Context(), tt.method, tt.path, nil))
if action != tt.action || kind != tt.kind || id != tt.id {
t.Fatalf("accessRequest = %q on %q (%q), want %q on %q (%q)", action, kind, id, tt.action, tt.kind, tt.id)
}
})
}
}
func TestPersonalTokensWithoutPerson(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} {
t.Run(method, func(t *testing.T) {
@@ -231,11 +260,11 @@ func TestPersonalTokensWithoutPerson(t *testing.T) {
rec := httptest.NewRecorder()
switch method {
case http.MethodGet:
s.handlePersonalTokensList(rec, req)
newIdentitiesAPI(s).handlePersonalTokensList(rec, req)
case http.MethodPost:
s.handlePersonalTokenCreate(rec, req)
newIdentitiesAPI(s).handlePersonalTokenCreate(rec, req)
case http.MethodDelete:
s.handlePersonalTokenRevoke(rec, req)
newIdentitiesAPI(s).handlePersonalTokenRevoke(rec, req)
}
if method == http.MethodGet {
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"available":false`) {
+388
View File
@@ -0,0 +1,388 @@
package webui
import (
"context"
"errors"
"log/slog"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
// bindingsAPI owns the /api/bindings routes and the binding dispatch
// sub-resource. The composition root constructs it only when the binding
// store is configured; otherwise Server mounts a 503 stub, so a.bindings is
// always non-nil here. dispatches and mappings stay optional: lastOutcome
// degrades to nil and checkedBinding answers 503, as before.
type bindingsAPI struct {
bindings storecontract.BindingStore
dispatches storecontract.DispatchLedger
mappings storecontract.MappingStore
log *slog.Logger
authorizeTaskMutation func(http.ResponseWriter, *http.Request) bool
workflowEntry func(context.Context, string) (task.WorkflowDefinitionEntry, bool, error)
workflowEnablement func(context.Context) (task.WorkflowEnablement, int64, error)
unsignedSources func(context.Context) (map[string]bool, error)
dispatchesFor func(func(string) (storecontract.DispatchFilter, bool)) http.HandlerFunc
}
func newBindingsAPI(s *Server) *bindingsAPI {
return &bindingsAPI{
bindings: s.Bindings,
dispatches: s.Dispatches,
mappings: s.Mappings,
log: s.Log,
authorizeTaskMutation: s.authorizeTaskMutation,
workflowEntry: newWorkflowsAPI(s).workflowEntry,
workflowEnablement: newWorkflowsAPI(s).workflowEnablement,
unsignedSources: s.unsignedSources,
dispatchesFor: s.handleDispatches,
}
}
// bindingsRoutes lists the method+path patterns the bindings module owns, so
// the 503 stub mounts exactly the same routes.
var bindingsRoutes = []string{
"GET /api/bindings",
"POST /api/bindings",
"GET /api/bindings/{id}",
"PATCH /api/bindings/{id}",
"DELETE /api/bindings/{id}",
"POST /api/bindings/{id}/approve",
"POST /api/bindings/{id}/pause",
"POST /api/bindings/{id}/resume",
"GET /api/bindings/{id}/dispatches",
}
// notConfigured answers every request with msg and 503, matching what the
// handlers did when their store field was nil.
func notConfigured(msg string) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, msg, http.StatusServiceUnavailable)
}
}
func (a *bindingsAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/bindings", a.handleBindingsList)
mux.HandleFunc("POST /api/bindings", a.handleBindingCreate)
mux.HandleFunc("GET /api/bindings/{id}", a.handleBindingGet)
mux.HandleFunc("PATCH /api/bindings/{id}", a.handleBindingUpdate)
mux.HandleFunc("DELETE /api/bindings/{id}", a.handleBindingDelete)
mux.HandleFunc("POST /api/bindings/{id}/approve", a.handleBindingTransition("approve", storecontract.BindingStore.ApproveBinding))
mux.HandleFunc("POST /api/bindings/{id}/pause", a.handleBindingTransition("pause", storecontract.BindingStore.PauseBinding))
mux.HandleFunc("POST /api/bindings/{id}/resume", a.handleBindingTransition("resume", storecontract.BindingStore.ResumeBinding))
mux.HandleFunc("GET /api/bindings/{id}/dispatches", a.dispatchesFor(func(id string) (storecontract.DispatchFilter, bool) {
return storecontract.DispatchFilter{BindingID: id}, id != ""
}))
}
// bindingRequest is the wire shape POST /api/bindings and
// PATCH /api/bindings/{id} both accept. ID/Version/Status/CreatedAt/UpdatedAt
// are server-assigned (or server-driven), never taken from the request body.
type bindingRequest struct {
Name string `json:"name"`
Matcher binding.Matcher `json:"matcher"`
MappingID string `json:"mapping_id"`
Filter string `json:"filter"`
Workflow string `json:"workflow"`
// Owner and Repo optionally pin the binding to one configured repo,
// for multi-repo deployments. Both empty is valid (falls back to the
// daemon's single-configured-repo behaviour); binding.Validate
// rejects setting only one.
Owner string `json:"owner"`
Repo string `json:"repo"`
// RepoParam takes the repository from a mapped parameter instead.
RepoParam string `json:"repo_param"`
Inputs map[string]binding.InputSource `json:"inputs"`
}
// bindingView is a listed binding with its source's signing state, so the
// list can flag a binding that dispatches unsigned events.
type bindingView struct {
binding.Binding
Unsigned bool `json:"unsigned"`
// WorkflowDisabled marks a binding whose org has disabled the workflow it
// targets; it does not dispatch until the workflow is enabled again.
WorkflowDisabled bool `json:"workflow_disabled"`
// LastOutcome is the binding's newest ledger row: the task it started or
// the reason it started none.
LastOutcome *storecontract.Dispatch `json:"last_outcome,omitempty"`
}
func (a *bindingsAPI) handleBindingsList(w http.ResponseWriter, r *http.Request) {
bindings, err := a.bindings.ListBindings(r.Context())
if err != nil {
a.log.ErrorContext(r.Context(), "list bindings", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
unsigned, err := a.unsignedSources(r.Context())
if err != nil {
a.log.ErrorContext(r.Context(), "list sources", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
enablement, _, err := a.workflowEnablement(r.Context())
if err != nil {
a.log.ErrorContext(r.Context(), "workflow enablement", "err", err)
http.Error(w, "list bindings failed", http.StatusInternalServerError)
return
}
views := make([]bindingView, 0, len(bindings))
for _, b := range bindings {
if !listedIn(r, b.WorkspaceID) {
continue
}
views = append(views, bindingView{
Binding: b, Unsigned: unsigned[b.Matcher.Source], WorkflowDisabled: !enablement.Enabled(b.OrgID, b.Workflow),
LastOutcome: a.lastOutcome(r.Context(), b.ID),
})
}
writeJSON(w, map[string]any{"bindings": views})
}
// lastOutcome returns a binding's newest dispatch, or nil when it has none or
// the ledger is unreadable.
func (a *bindingsAPI) lastOutcome(ctx context.Context, bindingID string) *storecontract.Dispatch {
if a.dispatches == nil {
return nil
}
rows, err := a.dispatches.ListDispatches(ctx, storecontract.DispatchFilter{BindingID: bindingID, Limit: 1})
if err != nil {
a.log.WarnContext(ctx, "binding last outcome", "binding", bindingID, "err", err)
return nil
}
if len(rows) == 0 {
return nil
}
return &rows[0]
}
func (a *bindingsAPI) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
if !a.authorizeTaskMutation(w, r) {
return
}
req, ok := decodeBody[bindingRequest](w, r)
if !ok {
return
}
b, ok := a.checkedBinding(w, r, "", req)
if !ok {
return
}
id, err := a.bindings.InsertBinding(r.Context(), b)
if err != nil {
a.log.ErrorContext(r.Context(), "insert binding", "err", err)
http.Error(w, "create binding failed", http.StatusInternalServerError)
return
}
created, err := a.bindings.GetBinding(r.Context(), id)
if err != nil || created == nil {
a.log.ErrorContext(r.Context(), "get binding after insert", "err", err, "id", id)
http.Error(w, "create binding failed", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, created)
}
func (a *bindingsAPI) handleBindingGet(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
b, err := a.bindings.GetBinding(r.Context(), id)
if err != nil {
a.log.ErrorContext(r.Context(), "get binding", "err", err, "id", id)
http.Error(w, "get binding failed", http.StatusInternalServerError)
return
}
if b == nil {
http.Error(w, "binding not found", http.StatusNotFound)
return
}
writeJSON(w, b)
}
func (a *bindingsAPI) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
if !a.authorizeTaskMutation(w, r) {
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
req, ok := decodeBody[bindingRequest](w, r)
if !ok {
return
}
b, ok := a.checkedBinding(w, r, id, req)
if !ok {
return
}
if err := a.bindings.UpdateBinding(r.Context(), b); err != nil {
switch {
case errors.Is(err, storecontract.ErrBindingNotFound):
http.Error(w, "binding not found", http.StatusNotFound)
default:
a.log.ErrorContext(r.Context(), "update binding", "err", err, "id", id)
http.Error(w, "update binding failed", http.StatusInternalServerError)
}
return
}
updated, err := a.bindings.GetBinding(r.Context(), id)
if err != nil || updated == nil {
a.log.ErrorContext(r.Context(), "get binding after update", "err", err, "id", id)
http.Error(w, "update binding failed", http.StatusInternalServerError)
return
}
writeJSON(w, updated)
}
func (a *bindingsAPI) handleBindingDelete(w http.ResponseWriter, r *http.Request) {
if !a.authorizeTaskMutation(w, r) {
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
if err := a.bindings.DeleteBinding(r.Context(), id); err != nil {
if errors.Is(err, storecontract.ErrBindingNotFound) {
http.Error(w, "binding not found", http.StatusNotFound)
return
}
a.log.ErrorContext(r.Context(), "delete binding", "err", err, "id", id)
http.Error(w, "delete binding failed", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleBindingTransition serves one binding lifecycle command (approve,
// pause, resume) and answers the binding as it now stands.
func (a *bindingsAPI) handleBindingTransition(verb string, apply func(storecontract.BindingStore, context.Context, string) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !a.authorizeTaskMutation(w, r) {
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "invalid binding id", http.StatusBadRequest)
return
}
if err := apply(a.bindings, r.Context(), id); err != nil {
switch {
case errors.Is(err, storecontract.ErrBindingNotFound):
http.Error(w, "binding not found", http.StatusNotFound)
case errors.Is(err, storecontract.ErrBindingTransition):
http.Error(w, "binding cannot "+verb+" from its current state", http.StatusConflict)
default:
a.log.ErrorContext(r.Context(), verb+" binding", "err", err, "id", id)
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
}
return
}
updated, err := a.bindings.GetBinding(r.Context(), id)
if err != nil || updated == nil {
a.log.ErrorContext(r.Context(), "get binding after "+verb, "err", err, "id", id)
http.Error(w, verb+" binding failed", http.StatusInternalServerError)
return
}
writeJSON(w, updated)
}
}
// checkedBinding builds the binding a create or update request describes and
// refuses it, having written the error, unless it is well-formed, its mapping
// exists, its filter compiles against the mapping's parameters, and its inputs
// and repository satisfy the workflow it targets.
func (a *bindingsAPI) checkedBinding(w http.ResponseWriter, r *http.Request, id string, req bindingRequest) (binding.Binding, bool) {
b := binding.Binding{
ID: id,
Name: req.Name,
Matcher: req.Matcher,
MappingID: req.MappingID,
Filter: req.Filter,
Workflow: req.Workflow,
Owner: req.Owner,
Repo: req.Repo,
RepoParam: req.RepoParam,
Inputs: req.Inputs,
Status: binding.StatusPendingApproval,
}
if err := b.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
entry, found, err := a.workflowEntry(r.Context(), req.Workflow)
if err != nil {
http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
if !found {
http.Error(w, "binding: workflow not found: "+req.Workflow, http.StatusBadRequest)
return binding.Binding{}, false
}
enabled, err := a.bindingWorkflowEnabled(r.Context(), id, req.Workflow)
if err != nil {
http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
if !enabled {
http.Error(w, "binding: workflow is disabled: "+req.Workflow, http.StatusConflict)
return binding.Binding{}, false
}
iface, err := task.ParseWorkflowInterface(entry.YAML)
if err != nil {
http.Error(w, "binding: workflow "+req.Workflow+": "+err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return binding.Binding{}, false
}
m, err := a.mappings.GetMapping(r.Context(), b.MappingID)
if err != nil {
a.log.ErrorContext(r.Context(), "get mapping for binding", "err", err, "mapping", b.MappingID)
http.Error(w, "get mapping failed", http.StatusInternalServerError)
return binding.Binding{}, false
}
if m == nil {
http.Error(w, "binding: mapping not found: "+b.MappingID, http.StatusBadRequest)
return binding.Binding{}, false
}
if _, err := binding.CompileFilter(b.Filter, m.Fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
if err := b.CheckWorkflow(iface, m.Fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return binding.Binding{}, false
}
return b, true
}
// bindingWorkflowEnabled reports whether the org owning binding id (the
// default org for a binding not yet created) has workflow enabled.
func (a *bindingsAPI) bindingWorkflowEnabled(ctx context.Context, id, workflow string) (bool, error) {
owner := org.DefaultOrgID
if id != "" {
existing, err := a.bindings.GetBinding(ctx, id)
if err != nil {
return false, err
}
if existing != nil {
owner = existing.OrgID
}
}
enablement, _, err := a.workflowEnablement(ctx)
return enablement.Enabled(owner, workflow), err
}
@@ -15,6 +15,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/lifecycle"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
@@ -135,20 +136,49 @@ type chatToolView struct {
TextOffset int `json:"text_offset,omitempty"`
}
func (s *Server) chatReady(w http.ResponseWriter) (*ChatService, bool) {
if s.Chat == nil || s.Chat.Contract == nil {
// chatAPI owns the /api/chat routes and the state they share: questions
// waiting for the browser's answer and files a turn offered for download.
type chatAPI struct {
chat *ChatService
updateReportPath string
configSource func() ConfigViewSource
asks chatAsks
files chatFiles
}
func newChatAPI(s *Server) *chatAPI {
return &chatAPI{chat: s.Chat, updateReportPath: s.UpdateReportPath, configSource: s.configSource}
}
func (a *chatAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/chat/sessions", a.handleChatSessions)
mux.HandleFunc("GET /api/chat/sessions/{id}/messages", a.handleChatMessages)
mux.HandleFunc("GET /api/chat/sessions/{id}/turns", a.handleChatTurns)
mux.HandleFunc("POST /api/chat/message", a.handleChatMessage)
mux.HandleFunc("POST /api/chat/stream", a.handleChatStream)
mux.HandleFunc("POST /api/chat/cancel", a.handleChatCancel)
mux.HandleFunc("POST /api/chat/answer", a.handleChatAnswer)
mux.HandleFunc("GET /api/chat/file/{token}", a.handleChatFile)
mux.HandleFunc("GET /api/chat/update", instanceOnly(a.handleChatUpdate))
mux.HandleFunc("POST /api/chat/update/defer", instanceOnly(a.handleChatUpdateDefer))
mux.HandleFunc("POST /api/chat/update/install", instanceOnly(a.handleChatUpdateInstall))
}
func (a *chatAPI) chatReady(w http.ResponseWriter) (*ChatService, bool) {
if a.chat == nil || a.chat.Contract == nil {
http.Error(w, "chat is not configured", http.StatusNotImplemented)
return nil, false
}
return s.Chat, true
return a.chat, true
}
func chatUpdateServiceConfigured(updates ChatUpdateService) bool {
return !lifecycle.IsNil(updates)
}
func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatSessions(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -159,7 +189,7 @@ func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
}
out := make([]messaging.SessionContext, 0, len(snapshot.Sessions))
for _, session := range snapshot.Sessions {
if s.ownsChatSession(r.Context(), session) {
if a.ownsChatSession(r.Context(), session) {
out = append(out, session)
}
}
@@ -180,8 +210,8 @@ func chatCommandSpecs(chat *ChatService) []messaging.CommandSpec {
return specs
}
func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatMessages(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -191,7 +221,7 @@ func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !found || !s.ownsChatSession(r.Context(), session) {
if !found || !a.ownsChatSession(r.Context(), session) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
@@ -211,8 +241,8 @@ func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
writeJSON(w, views)
}
func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatTurns(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -222,7 +252,7 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !found || !s.ownsChatSession(r.Context(), session) {
if !found || !a.ownsChatSession(r.Context(), session) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
@@ -249,7 +279,7 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
writeJSON(w, views)
}
func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (messaging.Inbound, bool) {
func (a *chatAPI) decodeChatMessage(w http.ResponseWriter, r *http.Request) (messaging.Inbound, bool) {
var req chatMessageRequest
// Base64 makes a clip a third larger than its bytes.
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxVoiceBytes*3/2)).Decode(&req); err != nil {
@@ -299,12 +329,12 @@ func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (mess
}, true
}
func (s *Server) handleChatMessage(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatMessage(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
msg, ok := s.decodeChatMessage(w, r)
msg, ok := a.decodeChatMessage(w, r)
if !ok {
return
}
@@ -397,20 +427,20 @@ func (s chatStreamSink) Media(event messaging.MediaEvent) {
// chatShowToolCalls reports config.ChatConfig.ShowToolCalls, false when no
// config is available.
func (s *Server) chatShowToolCalls(ctx context.Context) bool {
view, found, err := s.configSource()(ctx)
func (a *chatAPI) chatShowToolCalls(ctx context.Context) bool {
view, found, err := a.configSource()(ctx)
if err != nil || !found {
return false
}
return view.Chat.ShowToolCalls
}
func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatStream(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
msg, ok := s.decodeChatMessage(w, r)
msg, ok := a.decodeChatMessage(w, r)
if !ok {
return
}
@@ -433,13 +463,13 @@ func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "data: %s\n\n", payload)
flusher.Flush()
}
asker := dashboardAsker{asks: &s.chatAsks, write: func(frame chatStreamEvent) { writeChatEvent(frame, "") }}
asker := dashboardAsker{asks: &a.asks, write: func(frame chatStreamEvent) { writeChatEvent(frame, "") }}
events, err := chat.Contract.Stream(withDashboardAsks(r.Context(), asker), msg)
if err != nil {
writeChatEvent(chatStreamEvent{Type: "error", Text: err.Error()}, "")
return
}
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls(r.Context()), files: &s.chatFiles, owner: chatUser(r.Context())}
sink := chatStreamSink{showToolCalls: a.chatShowToolCalls(r.Context()), files: &a.files, owner: chatUser(r.Context())}
for event := range events {
sink.write = func(frame chatStreamEvent) { writeChatEvent(frame, event.SessionID) }
switch event.Kind {
@@ -453,8 +483,8 @@ func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
}
}
func (s *Server) handleChatCancel(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatCancel(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -477,7 +507,7 @@ func (s *Server) handleChatCancel(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !found || !s.ownsChatSession(r.Context(), session) {
if !found || !a.ownsChatSession(r.Context(), session) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
@@ -499,8 +529,8 @@ func writeUpdateCheckError(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusBadGateway)
}
func (s *Server) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -513,6 +543,11 @@ func (s *Server) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
writeUpdateCheckError(w, err)
return
}
// The snapshot carries when the installed release was committed on this
// host, so a canary can count its window from the actual install.
if _, at, ok := releaseupdate.LastInstall(updateStateDir()); ok {
snapshot.InstalledAt = at
}
writeJSON(w, map[string]any{
"snapshot": snapshot,
"available": snapshot.Available(),
@@ -520,8 +555,15 @@ func (s *Server) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
})
}
func (s *Server) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
// updateStateDir resolves the host's update state directory the same way the
// daemon does, so the dashboard reads the installed.json its transactions
// write.
func updateStateDir() string {
return configuration.UpdateStateDir()
}
func (a *chatAPI) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -541,8 +583,8 @@ func (s *Server) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]bool{"ok": true})
}
func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request) {
chat, ok := s.chatReady(w)
func (a *chatAPI) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
return
}
@@ -579,7 +621,7 @@ func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request)
}()
progress := make([]string, 0, 4)
meta := releaseupdate.InstallMeta{Channel: "webui", ReportPath: s.UpdateReportPath}
meta := releaseupdate.InstallMeta{Channel: "webui", ReportPath: a.updateReportPath}
result, err := chat.Updates.Install(r.Context(), fresh, meta, func(message string) { progress = append(progress, message) })
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
@@ -605,6 +647,6 @@ func chatUser(ctx context.Context) string {
return ""
}
func (s *Server) ownsChatSession(ctx context.Context, session messaging.SessionContext) bool {
func (a *chatAPI) ownsChatSession(ctx context.Context, session messaging.SessionContext) bool {
return session.Source.Platform == "web" && session.Source.ThreadID == chatUser(ctx)
}
@@ -189,13 +189,13 @@ type chatAnswerRequest struct {
}
// handleChatAnswer delivers the operator's answer to the ask a turn waits on.
func (s *Server) handleChatAnswer(w http.ResponseWriter, r *http.Request) {
func (a *chatAPI) handleChatAnswer(w http.ResponseWriter, r *http.Request) {
var req chatAnswerRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ID == "" {
http.Error(w, "id is required", http.StatusBadRequest)
return
}
if !s.chatAsks.answer(req.ID, req.Answer, chatUser(r.Context())) {
if !a.asks.answer(req.ID, req.Answer, chatUser(r.Context())) {
http.Error(w, "that question is no longer waiting", http.StatusNotFound)
return
}
@@ -72,8 +72,8 @@ func (c *chatFiles) lookup(token string) (chatFile, bool) {
return f, true
}
func (s *Server) handleChatFile(w http.ResponseWriter, r *http.Request) {
f, ok := s.chatFiles.lookup(r.PathValue("token"))
func (a *chatAPI) handleChatFile(w http.ResponseWriter, r *http.Request) {
f, ok := a.files.lookup(r.PathValue("token"))
if !ok || f.owner != chatUser(r.Context()) {
http.Error(w, "that file is no longer available", http.StatusNotFound)
return
@@ -19,10 +19,10 @@ func TestChatFileDownload(t *testing.T) {
t.Fatal(err)
}
now := time.Now()
srv := &Server{}
srv.chatFiles.now = func() time.Time { return now }
token := srv.chatFiles.offer(path, "")
private := srv.chatFiles.offerFor(path, "", "alice")
srv := newChatAPI(&Server{})
srv.files.now = func() time.Time { return now }
token := srv.files.offer(path, "")
private := srv.files.offerFor(path, "", "alice")
tests := []struct {
name string
@@ -41,7 +41,7 @@ func TestChatFileDownload(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv.chatFiles.now = func() time.Time { return now.Add(tt.after) }
srv.files.now = func() time.Time { return now.Add(tt.after) }
ctx := t.Context()
if tt.user != "" {
ctx = WithActingIdentity(ctx, identity.Identity{ID: identity.IdentityID(tt.user)})
+6 -6
View File
@@ -36,11 +36,11 @@ func (ownedChat) Cancel(context.Context, string) (messaging.ChatCancellation, er
func TestWebChatOwnership(t *testing.T) {
for _, route := range []struct {
name, body string
handler func(*Server, http.ResponseWriter, *http.Request)
handler func(*chatAPI, http.ResponseWriter, *http.Request)
}{
{"messages", "", (*Server).handleChatMessages},
{"turns", "", (*Server).handleChatTurns},
{"cancel", `{"session_id":"private"}`, (*Server).handleChatCancel},
{"messages", "", (*chatAPI).handleChatMessages},
{"turns", "", (*chatAPI).handleChatTurns},
{"cancel", `{"session_id":"private"}`, (*chatAPI).handleChatCancel},
} {
for _, user := range []string{"alice", "bob"} {
t.Run(route.name+"/"+user, func(t *testing.T) {
@@ -49,7 +49,7 @@ func TestWebChatOwnership(t *testing.T) {
req.SetPathValue("id", "private")
rec := httptest.NewRecorder()
srv := &Server{Chat: &ChatService{Contract: ownedChat{}}}
route.handler(srv, rec, req)
route.handler(newChatAPI(srv), rec, req)
want := 200
if user != "alice" {
want = 404
@@ -65,7 +65,7 @@ func TestWebChatOwnership(t *testing.T) {
func TestWebChatSenderCannotBeSuppliedByBrowser(t *testing.T) {
ctx := WithActingIdentity(t.Context(), identity.Identity{ID: "alice"})
req := httptest.NewRequestWithContext(ctx, "POST", "https://archie.example/api/chat/message", strings.NewReader(`{"channel_id":"browser-channel","text":"hello","sender_id":"bob","thread_id":"bob"}`))
value, ok := (&Server{}).decodeChatMessage(httptest.NewRecorder(), req)
value, ok := newChatAPI(&Server{}).decodeChatMessage(httptest.NewRecorder(), req)
if !ok {
t.Fatal("message refused")
}
@@ -1,6 +1,7 @@
package webui
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
@@ -46,12 +47,30 @@ type controlPlaneHistoryResponse struct {
Revisions []controlPlaneRevision `json:"revisions"`
}
func (s *Server) handleControlPlaneCatalog(w http.ResponseWriter, r *http.Request) {
if s.ControlPlane == nil {
// controlPlaneAPI owns the generic /api/control-plane resource routes. A nil
// client answers 503.
type controlPlaneAPI struct {
controlPlane controlpb.ControlPlaneServiceClient
actorNames func(context.Context) func(string) string
}
func newControlPlaneAPI(s *Server) *controlPlaneAPI {
return &controlPlaneAPI{controlPlane: s.ControlPlane, actorNames: s.actorNames}
}
func (a *controlPlaneAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/control-plane/catalog", a.handleControlPlaneCatalog)
mux.HandleFunc("GET /api/control-plane/resources/{kind}", a.handleControlPlaneQuery)
mux.HandleFunc("GET /api/control-plane/resources/{kind}/history", a.handleControlPlaneHistory)
mux.HandleFunc("POST /api/control-plane/resources/{kind}/commands/{command}", a.handleControlPlaneCommand)
}
func (a *controlPlaneAPI) handleControlPlaneCatalog(w http.ResponseWriter, r *http.Request) {
if a.controlPlane == nil {
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
return
}
response, err := s.ControlPlane.Catalog(r.Context(), &controlpb.CatalogRequest{})
response, err := a.controlPlane.Catalog(r.Context(), &controlpb.CatalogRequest{})
if err != nil {
writeControlPlaneError(w, err)
return
@@ -59,12 +78,12 @@ func (s *Server) handleControlPlaneCatalog(w http.ResponseWriter, r *http.Reques
writeJSON(w, response)
}
func (s *Server) handleControlPlaneQuery(w http.ResponseWriter, r *http.Request) {
if s.ControlPlane == nil {
func (a *controlPlaneAPI) handleControlPlaneQuery(w http.ResponseWriter, r *http.Request) {
if a.controlPlane == nil {
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
return
}
response, err := s.ControlPlane.Query(r.Context(), &controlpb.QueryRequest{Kind: r.PathValue("kind")})
response, err := a.controlPlane.Query(r.Context(), &controlpb.QueryRequest{Kind: r.PathValue("kind")})
if err != nil {
writeControlPlaneError(w, err)
return
@@ -72,18 +91,18 @@ func (s *Server) handleControlPlaneQuery(w http.ResponseWriter, r *http.Request)
writeJSON(w, controlPlaneResourceResponse{Resource: controlPlaneResourceView(response.Resource)})
}
func (s *Server) handleControlPlaneHistory(w http.ResponseWriter, r *http.Request) {
if s.ControlPlane == nil {
func (a *controlPlaneAPI) handleControlPlaneHistory(w http.ResponseWriter, r *http.Request) {
if a.controlPlane == nil {
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
return
}
response, err := s.ControlPlane.History(r.Context(), &controlpb.HistoryRequest{Kind: r.PathValue("kind")})
response, err := a.controlPlane.History(r.Context(), &controlpb.HistoryRequest{Kind: r.PathValue("kind")})
if err != nil {
writeControlPlaneError(w, err)
return
}
revisions := make([]controlPlaneRevision, 0, len(response.Revisions))
actorName := s.actorNames(r.Context())
actorName := a.actorNames(r.Context())
for _, revision := range response.Revisions {
// The value is real, not redacted: the dashboard stages a revision and
// applies it as a replace, so a redacted value would restore the marker.
@@ -100,8 +119,8 @@ func (s *Server) handleControlPlaneHistory(w http.ResponseWriter, r *http.Reques
writeJSON(w, controlPlaneHistoryResponse{Revisions: revisions})
}
func (s *Server) handleControlPlaneCommand(w http.ResponseWriter, r *http.Request) {
if s.ControlPlane == nil {
func (a *controlPlaneAPI) handleControlPlaneCommand(w http.ResponseWriter, r *http.Request) {
if a.controlPlane == nil {
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
return
}
@@ -115,7 +134,7 @@ func (s *Server) handleControlPlaneCommand(w http.ResponseWriter, r *http.Reques
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
response, err := s.ControlPlane.Command(r.Context(), &controlpb.CommandRequest{
response, err := a.controlPlane.Command(r.Context(), &controlpb.CommandRequest{
Kind: r.PathValue("kind"), Command: r.PathValue("command"), ValueJson: request.Value,
ExpectedVersion: request.ExpectedVersion, Actor: string(audit.ActorID),
Source: audit.Source, RequestId: audit.RequestID,
@@ -2,12 +2,39 @@ package webui
import (
"errors"
"log/slog"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// eventTypesAPI owns the /api/event-types routes. eventTypes and captures stay
// optional: the list answers {"enabled": false} with no store, and proposals
// are empty without captures, as before.
type eventTypesAPI struct {
eventTypes storecontract.EventTypeStore
captures storecontract.CaptureStore
log *slog.Logger
authorize func(http.ResponseWriter, *http.Request) bool
}
func newEventTypesAPI(s *Server) *eventTypesAPI {
return &eventTypesAPI{
eventTypes: s.EventTypes,
captures: s.Captures,
log: s.Log,
authorize: s.authorizeTaskMutation,
}
}
func (a *eventTypesAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/event-types", a.handleEventTypes)
mux.HandleFunc("POST /api/event-types", a.handleEventTypeCreate)
mux.HandleFunc("PUT /api/event-types/{id}", a.handleEventTypeUpdate)
mux.HandleFunc("DELETE /api/event-types/{id}", a.handleEventTypeDelete)
}
// proposalScanLimit bounds how many recent captures are grouped into
// proposals on one read.
const proposalScanLimit = 500
@@ -37,22 +64,22 @@ type eventTypeUpdate struct {
// handleEventTypes lists the named event types and the proposals grouped from
// recent captures that were unidentified on arrival and still match no type.
func (s *Server) handleEventTypes(w http.ResponseWriter, r *http.Request) {
if s.EventTypes == nil {
func (a *eventTypesAPI) handleEventTypes(w http.ResponseWriter, r *http.Request) {
if a.eventTypes == nil {
writeJSON(w, map[string]any{"enabled": false, "event_types": []any{}, "proposals": []any{}})
return
}
types, err := s.EventTypes.ListEventTypes(r.Context())
types, err := a.eventTypes.ListEventTypes(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list event types", "err", err)
a.log.ErrorContext(r.Context(), "list event types", "err", err)
http.Error(w, "list event types failed", http.StatusInternalServerError)
return
}
proposals := []eventtype.Proposal{}
if s.Captures != nil {
captures, err := s.Captures.ListCaptures(r.Context(), proposalScanLimit)
if a.captures != nil {
captures, err := a.captures.ListCaptures(r.Context(), proposalScanLimit)
if err != nil {
s.Log.ErrorContext(r.Context(), "list captures for proposals", "err", err)
a.log.ErrorContext(r.Context(), "list captures for proposals", "err", err)
http.Error(w, "list captures failed", http.StatusInternalServerError)
return
}
@@ -86,11 +113,11 @@ func unmatchedCaptures(types []eventtype.EventType, captures []storecontract.Cap
return out
}
func (s *Server) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *eventTypesAPI) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.EventTypes == nil {
if a.eventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return
}
@@ -105,9 +132,9 @@ func (s *Server) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
if req.Rule != nil {
t.Rule = *req.Rule
}
id, err := s.EventTypes.InsertEventType(r.Context(), t)
id, err := a.eventTypes.InsertEventType(r.Context(), t)
if err != nil {
s.writeEventTypeError(w, "create", err)
a.writeEventTypeError(w, "create", err)
return
}
t.ID = id
@@ -115,11 +142,11 @@ func (s *Server) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
writeJSON(w, t)
}
func (s *Server) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *eventTypesAPI) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.EventTypes == nil {
if a.eventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return
}
@@ -129,29 +156,29 @@ func (s *Server) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
}
// Source is not editable: the store validates against the stored one.
t := eventtype.EventType{ID: r.PathValue("id"), Name: req.Name, Rule: req.Rule}
if err := s.EventTypes.UpdateEventType(r.Context(), t); err != nil {
s.writeEventTypeError(w, "update", err)
if err := a.eventTypes.UpdateEventType(r.Context(), t); err != nil {
a.writeEventTypeError(w, "update", err)
return
}
writeJSON(w, map[string]string{"id": t.ID})
}
func (s *Server) handleEventTypeDelete(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *eventTypesAPI) handleEventTypeDelete(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.EventTypes == nil {
if a.eventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return
}
if err := s.EventTypes.DeleteEventType(r.Context(), r.PathValue("id")); err != nil {
s.writeEventTypeError(w, "delete", err)
if err := a.eventTypes.DeleteEventType(r.Context(), r.PathValue("id")); err != nil {
a.writeEventTypeError(w, "delete", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) writeEventTypeError(w http.ResponseWriter, action string, err error) {
func (a *eventTypesAPI) writeEventTypeError(w http.ResponseWriter, action string, err error) {
switch {
case errors.Is(err, eventtype.ErrOverlap):
http.Error(w, "this rule can match events another type on the source already matches", http.StatusConflict)
@@ -160,7 +187,7 @@ func (s *Server) writeEventTypeError(w http.ResponseWriter, action string, err e
case errors.Is(err, storecontract.ErrEventTypeNotFound):
http.Error(w, "event type not found", http.StatusNotFound)
default:
s.Log.Error(action+" event type", "err", err)
a.log.Error(action+" event type", "err", err)
http.Error(w, action+" event type failed", http.StatusInternalServerError)
}
}
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"slices"
"strings"
@@ -13,6 +14,32 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
// extensionsAPI owns the /api/extensions routes. Handlers answer 503 until
// both the package surface and the control plane are wired.
type extensionsAPI struct {
packages storepkg.Installations
controlPlane controlpb.ControlPlaneServiceClient
log *slog.Logger
}
func newExtensionsAPI(s *Server) *extensionsAPI {
return &extensionsAPI{packages: s.Packages, controlPlane: s.ControlPlane, log: s.Log}
}
func (a *extensionsAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/extensions", a.handleExtensions)
mux.HandleFunc("POST /api/extensions", a.handleExtensionInstall)
mux.HandleFunc("GET /api/extensions/catalogue", a.handleCatalogue)
mux.HandleFunc("POST /api/extensions/catalogue/{name}/install", a.handleCatalogueInstall)
mux.HandleFunc("POST /api/extensions/{name}/accept", a.handleExtensionAccept)
mux.HandleFunc("POST /api/extensions/{name}/update", a.handleExtensionUpdate)
mux.HandleFunc("POST /api/extensions/{name}/approve-update", a.handleExtensionApproveUpdate)
mux.HandleFunc("POST /api/extensions/{name}/rollback", a.handleExtensionRollback)
mux.HandleFunc("PUT /api/extensions/{name}/update-policy", a.handleExtensionUpdatePolicy)
mux.HandleFunc("PUT /api/extensions/{name}/enabled", a.handleExtensionEnabled)
mux.HandleFunc("DELETE /api/extensions/{name}", a.handleExtensionRemove)
}
type authorityView struct {
CredentialServices []string `json:"credential_services"`
EgressHosts []string `json:"egress_hosts"`
@@ -107,9 +134,9 @@ func extensionView(p storepkg.Installed, enabled bool) ExtensionView {
// extensionSettings reads the extension-settings resource and the version a
// replacement must name.
func (s *Server) extensionSettings(ctx context.Context) (controlplanerpc.ExtensionSettings, int64, error) {
func (a *extensionsAPI) extensionSettings(ctx context.Context) (controlplanerpc.ExtensionSettings, int64, error) {
var doc controlplanerpc.ExtensionSettings
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: controlplanerpc.ExtensionSettingsKind})
response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: controlplanerpc.ExtensionSettingsKind})
if err != nil {
return doc, 0, err
}
@@ -123,7 +150,7 @@ func (s *Server) extensionSettings(ctx context.Context) (controlplanerpc.Extensi
}
// putExtensionSettings replaces the extension-settings resource at version.
func (s *Server) putExtensionSettings(ctx context.Context, doc controlplanerpc.ExtensionSettings, version int64) error {
func (a *extensionsAPI) putExtensionSettings(ctx context.Context, doc controlplanerpc.ExtensionSettings, version int64) error {
value, err := json.Marshal(doc)
if err != nil {
return err
@@ -132,7 +159,7 @@ func (s *Server) putExtensionSettings(ctx context.Context, doc controlplanerpc.E
if err != nil {
return err
}
_, err = s.ControlPlane.Command(ctx, &controlpb.CommandRequest{
_, err = a.controlPlane.Command(ctx, &controlpb.CommandRequest{
Kind: controlplanerpc.ExtensionSettingsKind, Command: "replace", ValueJson: value,
ExpectedVersion: version, Actor: string(audit.ActorID), Source: audit.Source, RequestId: audit.RequestID,
})
@@ -161,8 +188,8 @@ func withExtension(doc controlplanerpc.ExtensionSettings, name string, enabled *
return next
}
func (s *Server) extensionsReady(w http.ResponseWriter) bool {
if s.Packages == nil || s.ControlPlane == nil {
func (a *extensionsAPI) extensionsReady(w http.ResponseWriter) bool {
if a.packages == nil || a.controlPlane == nil {
http.Error(w, "extensions unavailable", http.StatusServiceUnavailable)
return false
}
@@ -186,16 +213,16 @@ func writePackageError(w http.ResponseWriter, err error) {
// handleExtensions lists the installed packages with their authority and
// enabled state.
func (s *Server) handleExtensions(w http.ResponseWriter, r *http.Request) {
if !s.extensionsReady(w) {
func (a *extensionsAPI) handleExtensions(w http.ResponseWriter, r *http.Request) {
if !a.extensionsReady(w) {
return
}
installed, err := s.Packages.ListInstalled(r.Context())
installed, err := a.packages.ListInstalled(r.Context())
if err != nil {
writePackageError(w, err)
return
}
doc, _, err := s.extensionSettings(r.Context())
doc, _, err := a.extensionSettings(r.Context())
if err != nil {
writeControlPlaneError(w, err)
return
@@ -219,15 +246,15 @@ type installExtensionRequest struct {
// handleExtensionInstall installs a digest-pinned package. It does not enable
// it and does not accept its authority: both are separate operator actions.
func (s *Server) handleExtensionInstall(w http.ResponseWriter, r *http.Request) {
if !s.extensionsReady(w) {
func (a *extensionsAPI) handleExtensionInstall(w http.ResponseWriter, r *http.Request) {
if !a.extensionsReady(w) {
return
}
request, ok := decodeBody[installExtensionRequest](w, r)
if !ok {
return
}
p, err := s.Packages.InstallPackage(r.Context(),
p, err := a.packages.InstallPackage(r.Context(),
strings.TrimSpace(request.Name), strings.TrimSpace(request.Reference), strings.TrimSpace(request.Digest))
if err != nil {
writePackageError(w, err)
@@ -238,17 +265,17 @@ func (s *Server) handleExtensionInstall(w http.ResponseWriter, r *http.Request)
// handleExtensionAccept records the operator's acceptance of exactly the
// authority the package declares.
func (s *Server) handleExtensionAccept(w http.ResponseWriter, r *http.Request) {
if !s.extensionsReady(w) {
func (a *extensionsAPI) handleExtensionAccept(w http.ResponseWriter, r *http.Request) {
if !a.extensionsReady(w) {
return
}
name := r.PathValue("name")
installed, err := s.Packages.GetInstalled(r.Context(), name)
installed, err := a.packages.GetInstalled(r.Context(), name)
if err != nil {
writePackageError(w, err)
return
}
p, err := s.Packages.AcceptPackageAuthority(r.Context(), name, installed.Descriptor.Authority)
p, err := a.packages.AcceptPackageAuthority(r.Context(), name, installed.Descriptor.Authority)
if err != nil {
writePackageError(w, err)
return
@@ -258,20 +285,20 @@ func (s *Server) handleExtensionAccept(w http.ResponseWriter, r *http.Request) {
// handleExtensionUpdate moves a package to the catalogue's digest: an update
// that adds no authority applies, one that does waits as pending.
func (s *Server) handleExtensionUpdate(w http.ResponseWriter, r *http.Request) {
s.packageTransition(w, r, s.Packages.UpdatePackage)
func (a *extensionsAPI) handleExtensionUpdate(w http.ResponseWriter, r *http.Request) {
a.packageTransition(w, r, a.packages.UpdatePackage)
}
// handleExtensionApproveUpdate applies the pending update and accepts the
// authority it declares.
func (s *Server) handleExtensionApproveUpdate(w http.ResponseWriter, r *http.Request) {
s.packageTransition(w, r, s.Packages.ApprovePackageUpdate)
func (a *extensionsAPI) handleExtensionApproveUpdate(w http.ResponseWriter, r *http.Request) {
a.packageTransition(w, r, a.packages.ApprovePackageUpdate)
}
// handleExtensionRollback restores the previous digest and its accepted
// authority.
func (s *Server) handleExtensionRollback(w http.ResponseWriter, r *http.Request) {
s.packageTransition(w, r, s.Packages.RollbackPackage)
func (a *extensionsAPI) handleExtensionRollback(w http.ResponseWriter, r *http.Request) {
a.packageTransition(w, r, a.packages.RollbackPackage)
}
type updatePolicyRequest struct {
@@ -280,15 +307,15 @@ type updatePolicyRequest struct {
// handleExtensionUpdatePolicy sets whether the State Store updates a package
// on its own.
func (s *Server) handleExtensionUpdatePolicy(w http.ResponseWriter, r *http.Request) {
if !s.extensionsReady(w) {
func (a *extensionsAPI) handleExtensionUpdatePolicy(w http.ResponseWriter, r *http.Request) {
if !a.extensionsReady(w) {
return
}
request, ok := decodeBody[updatePolicyRequest](w, r)
if !ok {
return
}
p, err := s.Packages.SetPackageUpdatePolicy(r.Context(), r.PathValue("name"), request.Policy)
p, err := a.packages.SetPackageUpdatePolicy(r.Context(), r.PathValue("name"), request.Policy)
if err != nil {
writePackageError(w, err)
return
@@ -296,8 +323,8 @@ func (s *Server) handleExtensionUpdatePolicy(w http.ResponseWriter, r *http.Requ
writeJSON(w, extensionView(p, false))
}
func (s *Server) packageTransition(w http.ResponseWriter, r *http.Request, do func(context.Context, string) (storepkg.Installed, error)) {
if !s.extensionsReady(w) {
func (a *extensionsAPI) packageTransition(w http.ResponseWriter, r *http.Request, do func(context.Context, string) (storepkg.Installed, error)) {
if !a.extensionsReady(w) {
return
}
p, err := do(r.Context(), r.PathValue("name"))
@@ -313,8 +340,8 @@ type extensionEnabledRequest struct {
}
// handleExtensionEnabled enables or disables an installed extension.
func (s *Server) handleExtensionEnabled(w http.ResponseWriter, r *http.Request) {
if !s.extensionsReady(w) {
func (a *extensionsAPI) handleExtensionEnabled(w http.ResponseWriter, r *http.Request) {
if !a.extensionsReady(w) {
return
}
request, ok := decodeBody[extensionEnabledRequest](w, r)
@@ -322,16 +349,16 @@ func (s *Server) handleExtensionEnabled(w http.ResponseWriter, r *http.Request)
return
}
name := r.PathValue("name")
if _, err := s.Packages.GetInstalled(r.Context(), name); err != nil {
if _, err := a.packages.GetInstalled(r.Context(), name); err != nil {
writePackageError(w, err)
return
}
doc, version, err := s.extensionSettings(r.Context())
doc, version, err := a.extensionSettings(r.Context())
if err != nil {
writeControlPlaneError(w, err)
return
}
if err := s.putExtensionSettings(r.Context(), withExtension(doc, name, &request.Enabled), version); err != nil {
if err := a.putExtensionSettings(r.Context(), withExtension(doc, name, &request.Enabled), version); err != nil {
writeControlPlaneError(w, err)
return
}
@@ -340,18 +367,18 @@ func (s *Server) handleExtensionEnabled(w http.ResponseWriter, r *http.Request)
// handleExtensionRemove uninstalls an extension and drops its setting, so a
// later reinstall does not start enabled.
func (s *Server) handleExtensionRemove(w http.ResponseWriter, r *http.Request) {
if !s.extensionsReady(w) {
func (a *extensionsAPI) handleExtensionRemove(w http.ResponseWriter, r *http.Request) {
if !a.extensionsReady(w) {
return
}
name := r.PathValue("name")
if err := s.Packages.RemoveInstalled(r.Context(), name); err != nil {
if err := a.packages.RemoveInstalled(r.Context(), name); err != nil {
writePackageError(w, err)
return
}
if doc, version, err := s.extensionSettings(r.Context()); err == nil {
if err := s.putExtensionSettings(r.Context(), withExtension(doc, name, nil), version); err != nil {
s.Log.WarnContext(r.Context(), "drop extension setting", "name", name, "err", err)
if doc, version, err := a.extensionSettings(r.Context()); err == nil {
if err := a.putExtensionSettings(r.Context(), withExtension(doc, name, nil), version); err != nil {
a.log.WarnContext(r.Context(), "drop extension setting", "name", name, "err", err)
}
}
writeJSON(w, map[string]any{"name": name, "removed": true})
@@ -365,16 +392,16 @@ type catalogueView struct {
}
// handleCatalogue lists the packages the verified catalogue offers.
func (s *Server) handleCatalogue(w http.ResponseWriter, r *http.Request) {
if !s.extensionsReady(w) {
func (a *extensionsAPI) handleCatalogue(w http.ResponseWriter, r *http.Request) {
if !a.extensionsReady(w) {
return
}
catalogue, err := s.Packages.ListCatalogue(r.Context())
catalogue, err := a.packages.ListCatalogue(r.Context())
if err != nil {
http.Error(w, "catalogue unavailable: "+err.Error(), http.StatusBadGateway)
return
}
installed, err := s.Packages.ListInstalled(r.Context())
installed, err := a.packages.ListInstalled(r.Context())
if err != nil {
writePackageError(w, err)
return
@@ -392,11 +419,11 @@ func (s *Server) handleCatalogue(w http.ResponseWriter, r *http.Request) {
// handleCatalogueInstall installs one catalogue package by name, at the digest
// the verified catalogue pins.
func (s *Server) handleCatalogueInstall(w http.ResponseWriter, r *http.Request) {
if !s.extensionsReady(w) {
func (a *extensionsAPI) handleCatalogueInstall(w http.ResponseWriter, r *http.Request) {
if !a.extensionsReady(w) {
return
}
p, err := s.Packages.InstallFromCatalogue(r.Context(), r.PathValue("name"))
p, err := a.packages.InstallFromCatalogue(r.Context(), r.PathValue("name"))
if err != nil {
writePackageError(w, err)
return
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"sort"
@@ -93,36 +94,56 @@ type harnessView struct {
Profiles []string `json:"profiles"`
}
// harnessAPI owns the /api/harness routes. Each dependency is optional and a
// handler answers 503 when the one it needs is absent.
type harnessAPI struct {
controlPlane controlpb.ControlPlaneServiceClient
secrets storecontract.HarnessSecretStore
terminal HarnessTerminal
log *slog.Logger
}
func newHarnessAPI(s *Server) *harnessAPI {
return &harnessAPI{controlPlane: s.ControlPlane, secrets: s.HarnessSecrets, terminal: s.HarnessTerminal, log: s.Log}
}
func (a *harnessAPI) logf(msg string, args ...any) { warnf(a.log, msg, args...) }
func (a *harnessAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/harness/bindings", a.handleHarnessBindings)
mux.HandleFunc("GET /api/harness/terminal", a.handleHarnessTerminal)
}
// handleHarnessBindings lists the org's credential bindings joined with
// their captured OAuth state. It requires both contracts the join reads: an
// unconfigured process answers 503 rather than rendering a page that claims
// the org has no bindings, which it cannot know.
func (s *Server) handleHarnessBindings(w http.ResponseWriter, r *http.Request) {
if s.ControlPlane == nil || s.HarnessSecrets == nil {
func (a *harnessAPI) handleHarnessBindings(w http.ResponseWriter, r *http.Request) {
if a.controlPlane == nil || a.secrets == nil {
http.Error(w, "harness bindings not configured", http.StatusServiceUnavailable)
return
}
orgID := string(org.OrgFromContext(r.Context()))
bindings, err := s.harnessBindings(r.Context(), orgID)
bindings, err := a.harnessBindings(r.Context(), orgID)
if err != nil {
s.logf("list harness bindings", "err", err)
a.logf("list harness bindings", "err", err)
http.Error(w, "list harness bindings failed", http.StatusBadGateway)
return
}
profiles, err := s.harnessProfiles(r.Context())
profiles, err := a.harnessProfiles(r.Context())
if err != nil {
s.logf("list harness profiles", "err", err)
a.logf("list harness profiles", "err", err)
http.Error(w, "list harness bindings failed", http.StatusBadGateway)
return
}
writeJSON(w, harnessView{Terminal: s.HarnessTerminal != nil, Bindings: bindings, Profiles: profiles})
writeJSON(w, harnessView{Terminal: a.terminal != nil, Bindings: bindings, Profiles: profiles})
}
// harnessBindings reads the credential-bindings document and each service's
// captured token state. A service with no captured set is not an error: it
// is exactly the state the setup terminal exists to change.
func (s *Server) harnessBindings(ctx context.Context, orgID string) ([]harnessBindingView, error) {
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: harnessBindingsKind})
func (a *harnessAPI) harnessBindings(ctx context.Context, orgID string) ([]harnessBindingView, error) {
response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: harnessBindingsKind})
if err != nil {
return nil, err
}
@@ -138,7 +159,7 @@ func (s *Server) harnessBindings(ctx context.Context, orgID string) ([]harnessBi
continue
}
view := harnessBindingView{Service: doc.Service}
secret, err := s.HarnessSecrets.GetHarnessSecret(ctx, orgID, doc.Service)
secret, err := a.secrets.GetHarnessSecret(ctx, orgID, doc.Service)
switch {
case err == nil:
view.Captured = true
@@ -163,8 +184,8 @@ func (s *Server) harnessBindings(ctx context.Context, orgID string) ([]harnessBi
// harnessProfiles returns the agent profiles that name a Kit, sorted so the
// page's list does not depend on Go's map iteration order.
func (s *Server) harnessProfiles(ctx context.Context) ([]string, error) {
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: harnessProfilesKind})
func (a *harnessAPI) harnessProfiles(ctx context.Context) ([]string, error) {
response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: harnessProfilesKind})
if err != nil {
return nil, err
}
@@ -188,8 +209,8 @@ func (s *Server) harnessProfiles(ctx context.Context) ([]string, error) {
// a setup session opened for the named Kit profile. Opening the terminal is
// the update action on the secret, decided by the authorizer before this
// handler runs (authorize.go's route override).
func (s *Server) handleHarnessTerminal(w http.ResponseWriter, r *http.Request) {
if s.HarnessTerminal == nil {
func (a *harnessAPI) handleHarnessTerminal(w http.ResponseWriter, r *http.Request) {
if a.terminal == nil {
http.Error(w, "setup terminal not configured", http.StatusServiceUnavailable)
return
}
@@ -204,9 +225,9 @@ func (s *Server) handleHarnessTerminal(w http.ResponseWriter, r *http.Request) {
}
rows := terminalSize(r.URL.Query(), "rows", terminalDefaultRows)
cols := terminalSize(r.URL.Query(), "cols", terminalDefaultCols)
session, err := s.HarnessTerminal.Open(r.Context(), string(org.OrgFromContext(r.Context())), profile, rows, cols)
session, err := a.terminal.Open(r.Context(), string(org.OrgFromContext(r.Context())), profile, rows, cols)
if err != nil {
s.logf("open setup terminal", "err", err, "profile", profile)
a.logf("open setup terminal", "err", err, "profile", profile)
http.Error(w, "setup terminal failed", http.StatusBadGateway)
return
}
+209
View File
@@ -0,0 +1,209 @@
package webui
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"net/http"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
)
// identityTokenBinder is the one store-side operation the per-identity token
// route needs: binding a token to a NAMED identity. The remote client's
// caller-scoped PersonalTokens view cannot express that, so the store fronts
// it as its own RPC and the Client carries it under this name.
// identitiesAPI owns the identity routes and the signed-in person's API
// tokens. Either store may be nil; its routes then answer Unavailable.
type identitiesAPI struct {
identities identity.Repository
tokens identity.PersonalTokens
}
func newIdentitiesAPI(s *Server) *identitiesAPI {
return &identitiesAPI{identities: s.Identities, tokens: s.PersonalTokens}
}
func (a *identitiesAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/identities", instanceOnly(a.handleIdentitiesList))
mux.HandleFunc("POST /api/identities", instanceOnly(a.handleIdentityCreate))
mux.HandleFunc("POST /api/identities/{id}/{command}", instanceOnly(a.handleIdentityCommand))
mux.HandleFunc("POST /api/identities/{id}/tokens", instanceOnly(a.handleIdentityTokenCreate))
mux.HandleFunc("GET /api/tokens", a.handlePersonalTokensList)
mux.HandleFunc("POST /api/tokens", a.handlePersonalTokenCreate)
mux.HandleFunc("DELETE /api/tokens/{id}", a.handlePersonalTokenRevoke)
}
type identityTokenBinder interface {
BindPersonalToken(ctx context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, audit identity.Audit) error
}
// The production store client satisfies the route's narrow contract.
var _ identityTokenBinder = (*staterpc.Client)(nil)
type identityRequest struct {
DisplayName string `json:"display_name"`
Kind identity.Kind `json:"kind"`
ExpectedVersion int64 `json:"expected_version"`
}
func (a *identitiesAPI) handleIdentitiesList(w http.ResponseWriter, r *http.Request) {
if a.identities == nil {
http.Error(w, "identity store unavailable", http.StatusServiceUnavailable)
return
}
values, err := a.identities.List(r.Context())
if err != nil {
writeIdentityError(w, err)
return
}
if values == nil {
values = []identity.Identity{}
}
writeJSON(w, map[string]any{"identities": values})
}
func (a *identitiesAPI) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
request, ok := decodeBody[identityRequest](w, r)
if !ok {
return
}
id, err := randomIdentityID()
if err != nil {
http.Error(w, "cannot create identity ID", http.StatusInternalServerError)
return
}
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
value, err := identity.New(id, request.Kind, request.DisplayName)
if err == nil {
value, err = a.identities.Create(r.Context(), value, audit)
}
if err != nil {
writeIdentityError(w, err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, value)
}
func (a *identitiesAPI) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
request, ok := decodeBody[identityRequest](w, r)
if !ok {
return
}
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
command := identity.Command{Type: identity.CommandType(r.PathValue("command")), DisplayName: request.DisplayName}
value, err := a.identities.Apply(r.Context(), identity.IdentityID(r.PathValue("id")), request.ExpectedVersion, command, audit)
if err != nil {
writeIdentityError(w, err)
return
}
writeJSON(w, value)
}
// handleIdentityTokenCreate issues an API token for one named identity, which
// is how a non-user identity gets its bearer credential: a person's token
// comes from /api/tokens, a service account's from here. The raw token is
// returned exactly once; the store keeps only its hash.
func (a *identitiesAPI) handleIdentityTokenCreate(w http.ResponseWriter, r *http.Request) {
id := identity.IdentityID(r.PathValue("id"))
if a.identities == nil {
http.Error(w, "identity store unavailable", http.StatusServiceUnavailable)
return
}
value, err := a.identities.Get(r.Context(), id)
if errors.Is(err, identity.ErrNotFound) {
http.Error(w, "No such identity.", http.StatusBadRequest)
return
}
if err != nil {
writeIdentityError(w, err)
return
}
if !value.CanAct() {
http.Error(w, "That identity may not act.", http.StatusConflict)
return
}
name, expiresAt, ok := decodeTokenRequest(w, r)
if !ok {
return
}
// The store side of the PersonalTokens contract binds a token to a named
// identity; the remote caller's view only ever names its own principal.
binder, ok := a.tokens.(identityTokenBinder)
if !ok {
http.Error(w, "identity token binding unavailable", http.StatusServiceUnavailable)
return
}
raw, subject, err := identity.NewPersonalToken()
if err != nil {
http.Error(w, "cannot create token", http.StatusInternalServerError)
return
}
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
if err := binder.BindPersonalToken(r.Context(), id, subject, name, expiresAt, audit); err != nil {
writeIdentityError(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusCreated)
writeJSON(w, map[string]string{"id": subject.Subject, "token": raw})
}
// webAudit attributes a dashboard write to the request's own principal: the
// person the dashboard acts as. Only a request with no principal at all falls
// back to the System identity, which is a real identity the repository
// resolves, never a name the request could claim for itself.
func webAudit(ctx context.Context) (identity.Audit, error) {
id, err := newControlPlaneRequestID()
if err != nil {
return identity.Audit{}, err
}
actor := identity.SystemID
if p, ok := access.PrincipalFromContext(ctx); ok && p.IdentityID != "" {
actor = p.IdentityID
}
return identity.Audit{ActorID: actor, Source: "archie-ui", RequestID: id}, nil
}
func randomIdentityID() (identity.IdentityID, error) {
var value [16]byte
if _, err := rand.Read(value[:]); err != nil {
return "", err
}
value[6] = value[6]&0x0f | 0x40
value[8] = value[8]&0x3f | 0x80
encoded := hex.EncodeToString(value[:])
return identity.IdentityID(encoded[:8] + "-" + encoded[8:12] + "-" + encoded[12:16] + "-" + encoded[16:20] + "-" + encoded[20:]), nil
}
func writeIdentityError(w http.ResponseWriter, err error) {
code := http.StatusInternalServerError
switch {
case errors.Is(err, identity.ErrNotFound):
code = http.StatusNotFound
case errors.Is(err, identity.ErrConflict), errors.Is(err, org.ErrLastOwner):
code = http.StatusConflict
case errors.Is(err, identity.ErrInvalid), errors.Is(err, identity.ErrIllegalTransition), errors.Is(err, identity.ErrSystemImmutable):
code = http.StatusBadRequest
}
http.Error(w, strings.TrimSpace(err.Error()), code)
}
@@ -17,7 +17,20 @@ import (
// LogSource reads one service's bounded recent log over its contract.
type LogSource func(context.Context, logging.Query) (logging.Result, error)
func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
// logsAPI owns GET /api/logs. With no sources it reads this process's own
// feed; with neither it reports logs disabled.
type logsAPI struct {
sources map[string]LogSource
feed *logging.Feed
}
func newLogsAPI(s *Server) *logsAPI { return &logsAPI{sources: s.LogSources, feed: s.LogFeed} }
func (a *logsAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/logs", instanceOnly(a.handleLogs))
}
func (a *logsAPI) handleLogs(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
limit := logging.DefaultTailLines
if raw := strings.TrimSpace(q.Get("limit")); raw != "" {
@@ -30,9 +43,9 @@ func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
limit = min(parsed, logging.MaxTailLines)
}
}
sources := s.LogSources
sources := a.sources
if len(sources) == 0 {
sources = map[string]LogSource{presence.UI: func(_ context.Context, q logging.Query) (logging.Result, error) { return s.LogFeed.Read(q) }}
sources = map[string]LogSource{presence.UI: func(_ context.Context, q logging.Query) (logging.Result, error) { return a.feed.Read(q) }}
}
service := q.Get("service")
owner := service
@@ -55,7 +68,7 @@ func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
entries = entries[len(entries)-limit:]
truncated = true
}
writeJSON(w, map[string]any{"entries": entries, "components": components, "services": services, "errors": errors, "truncated": truncated, "disabled": len(s.LogSources) == 0 && s.LogFeed == nil})
writeJSON(w, map[string]any{"entries": entries, "components": components, "services": services, "errors": errors, "truncated": truncated, "disabled": len(a.sources) == 0 && a.feed == nil})
}
func readServiceLogs(ctx context.Context, sources map[string]LogSource, selected string, q logging.Query) ([]logging.Entry, map[string]string, bool) {
@@ -3,6 +3,7 @@ package webui
import (
"context"
"errors"
"log/slog"
"net/http"
"slices"
@@ -10,6 +11,49 @@ import (
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// mappingsAPI owns the /api/mappings routes. Constructed only when the
// mapping store is configured; Server mounts a 503 stub otherwise. eventTypes
// and captures stay optional inside (validateMapping and preview answer 503).
type mappingsAPI struct {
mappings storecontract.MappingStore
eventTypes storecontract.EventTypeStore
captures storecontract.CaptureStore
captureMaxEvents int
log *slog.Logger
authorize func(http.ResponseWriter, *http.Request) bool
}
func newMappingsAPI(s *Server) *mappingsAPI {
return &mappingsAPI{
mappings: s.Mappings,
eventTypes: s.EventTypes,
captures: s.Captures,
captureMaxEvents: s.CaptureMaxEvents,
log: s.Log,
authorize: s.authorizeTaskMutation,
}
}
// mappingsRoutes lists the method+path patterns the mappings module owns, so
// the 503 stub mounts exactly the same routes.
var mappingsRoutes = []string{
"GET /api/mappings",
"POST /api/mappings",
"GET /api/mappings/{id}",
"PATCH /api/mappings/{id}",
"DELETE /api/mappings/{id}",
"POST /api/mappings/preview",
}
func (a *mappingsAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/mappings", a.handleMappingsList)
mux.HandleFunc("POST /api/mappings", a.handleMappingCreate)
mux.HandleFunc("GET /api/mappings/{id}", a.handleMappingGet)
mux.HandleFunc("PATCH /api/mappings/{id}", a.handleMappingUpdate)
mux.HandleFunc("DELETE /api/mappings/{id}", a.handleMappingDelete)
mux.HandleFunc("POST /api/mappings/preview", a.handleMappingPreview)
}
// mappingRequest is the wire shape POST /api/mappings and
// PATCH /api/mappings/{id} both accept. ID/CreatedAt/UpdatedAt are
// server-assigned, never taken from the request body.
@@ -22,18 +66,18 @@ type mappingRequest struct {
// validateMapping checks m is well-formed and fits its event type's schema.
// It writes the refusal and returns false when it does not.
func (s *Server) validateMapping(w http.ResponseWriter, r *http.Request, m mapping.Mapping) bool {
func (a *mappingsAPI) validateMapping(w http.ResponseWriter, r *http.Request, m mapping.Mapping) bool {
if err := m.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return false
}
if s.EventTypes == nil {
if a.eventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return false
}
types, err := s.EventTypes.ListEventTypes(r.Context())
types, err := a.eventTypes.ListEventTypes(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list event types", "err", err)
a.log.ErrorContext(r.Context(), "list event types", "err", err)
http.Error(w, "list event types failed", http.StatusInternalServerError)
return false
}
@@ -50,14 +94,14 @@ func (s *Server) validateMapping(w http.ResponseWriter, r *http.Request, m mappi
return false
}
func (s *Server) handleMappingsList(w http.ResponseWriter, r *http.Request) {
if s.Mappings == nil {
func (a *mappingsAPI) handleMappingsList(w http.ResponseWriter, r *http.Request) {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
mappings, err := s.Mappings.ListMappings(r.Context())
mappings, err := a.mappings.ListMappings(r.Context())
if err != nil {
s.Log.ErrorContext(r.Context(), "list mappings", "err", err)
a.log.ErrorContext(r.Context(), "list mappings", "err", err)
http.Error(w, "list mappings failed", http.StatusInternalServerError)
return
}
@@ -65,11 +109,11 @@ func (s *Server) handleMappingsList(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{"mappings": mappings})
}
func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *mappingsAPI) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.Mappings == nil {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
@@ -78,18 +122,18 @@ func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
return
}
m := mapping.Mapping{Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields}
if !s.validateMapping(w, r, m) {
if !a.validateMapping(w, r, m) {
return
}
id, err := s.Mappings.InsertMapping(r.Context(), m)
id, err := a.mappings.InsertMapping(r.Context(), m)
if err != nil {
s.Log.ErrorContext(r.Context(), "insert mapping", "err", err)
a.log.ErrorContext(r.Context(), "insert mapping", "err", err)
http.Error(w, "create mapping failed", http.StatusInternalServerError)
return
}
created, err := s.Mappings.GetMapping(r.Context(), id)
created, err := a.mappings.GetMapping(r.Context(), id)
if err != nil || created == nil {
s.Log.ErrorContext(r.Context(), "get mapping after insert", "err", err, "id", id)
a.log.ErrorContext(r.Context(), "get mapping after insert", "err", err, "id", id)
http.Error(w, "create mapping failed", http.StatusInternalServerError)
return
}
@@ -97,8 +141,8 @@ func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
writeJSON(w, created)
}
func (s *Server) handleMappingGet(w http.ResponseWriter, r *http.Request) {
if s.Mappings == nil {
func (a *mappingsAPI) handleMappingGet(w http.ResponseWriter, r *http.Request) {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
@@ -107,9 +151,9 @@ func (s *Server) handleMappingGet(w http.ResponseWriter, r *http.Request) {
http.Error(w, "invalid mapping id", http.StatusBadRequest)
return
}
m, err := s.Mappings.GetMapping(r.Context(), id)
m, err := a.mappings.GetMapping(r.Context(), id)
if err != nil {
s.Log.ErrorContext(r.Context(), "get mapping", "err", err, "id", id)
a.log.ErrorContext(r.Context(), "get mapping", "err", err, "id", id)
http.Error(w, "get mapping failed", http.StatusInternalServerError)
return
}
@@ -120,11 +164,11 @@ func (s *Server) handleMappingGet(w http.ResponseWriter, r *http.Request) {
writeJSON(w, m)
}
func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *mappingsAPI) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.Mappings == nil {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
@@ -138,32 +182,32 @@ func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
return
}
m := mapping.Mapping{ID: id, Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields}
if !s.validateMapping(w, r, m) {
if !a.validateMapping(w, r, m) {
return
}
if err := s.Mappings.UpdateMapping(r.Context(), m); err != nil {
if err := a.mappings.UpdateMapping(r.Context(), m); err != nil {
if errors.Is(err, storecontract.ErrMappingNotFound) {
http.Error(w, "mapping not found", http.StatusNotFound)
return
}
s.Log.ErrorContext(r.Context(), "update mapping", "err", err, "id", id)
a.log.ErrorContext(r.Context(), "update mapping", "err", err, "id", id)
http.Error(w, "update mapping failed", http.StatusInternalServerError)
return
}
updated, err := s.Mappings.GetMapping(r.Context(), id)
updated, err := a.mappings.GetMapping(r.Context(), id)
if err != nil || updated == nil {
s.Log.ErrorContext(r.Context(), "get mapping after update", "err", err, "id", id)
a.log.ErrorContext(r.Context(), "get mapping after update", "err", err, "id", id)
http.Error(w, "update mapping failed", http.StatusInternalServerError)
return
}
writeJSON(w, updated)
}
func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
func (a *mappingsAPI) handleMappingDelete(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if s.Mappings == nil {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
@@ -172,12 +216,12 @@ func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) {
http.Error(w, "invalid mapping id", http.StatusBadRequest)
return
}
if err := s.Mappings.DeleteMapping(r.Context(), id); err != nil {
if err := a.mappings.DeleteMapping(r.Context(), id); err != nil {
if errors.Is(err, storecontract.ErrMappingNotFound) {
http.Error(w, "mapping not found", http.StatusNotFound)
return
}
s.Log.ErrorContext(r.Context(), "delete mapping", "err", err, "id", id)
a.log.ErrorContext(r.Context(), "delete mapping", "err", err, "id", id)
http.Error(w, "delete mapping failed", http.StatusInternalServerError)
return
}
@@ -192,12 +236,12 @@ type mappingPreviewRequest struct {
Fields []mapping.Field `json:"fields"`
}
func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
if s.Mappings == nil {
func (a *mappingsAPI) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
if a.mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return
}
if s.Captures == nil {
if a.captures == nil {
http.Error(w, "captures not configured", http.StatusServiceUnavailable)
return
}
@@ -205,9 +249,9 @@ func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
capture, err := s.captureByID(r.Context(), req.CaptureID)
capture, err := a.captureByID(r.Context(), req.CaptureID)
if err != nil {
s.Log.ErrorContext(r.Context(), "get capture for preview", "err", err, "capture_id", req.CaptureID)
a.log.ErrorContext(r.Context(), "get capture for preview", "err", err, "capture_id", req.CaptureID)
http.Error(w, "preview failed", http.StatusInternalServerError)
return
}
@@ -225,8 +269,8 @@ func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
// captureByID finds one captured event by ID. CaptureStore exposes only
// ListCaptures, so this scans the newest window rather than adding a new store
// method for a single low-volume caller.
func (s *Server) captureByID(ctx context.Context, id string) (*storecontract.CapturedEvent, error) {
captures, err := s.Captures.ListCaptures(ctx, mappingCaptureScanWindow(s.CaptureMaxEvents))
func (a *mappingsAPI) captureByID(ctx context.Context, id string) (*storecontract.CapturedEvent, error) {
captures, err := a.captures.ListCaptures(ctx, mappingCaptureScanWindow(a.captureMaxEvents))
if err != nil {
return nil, err
}
@@ -12,9 +12,37 @@ import (
"github.com/samcharles93/archie-core/internal/domain/org"
)
// orgsAPI owns the /api/orgs routes except selecting the current org, which
// sets a cookie and stays with the session code. memberIssuer is the provider
// the add-member route binds subjects under.
type orgsAPI struct {
orgs org.API
identities identity.Repository
subjects identity.SubjectBinding
memberIssuer func(*http.Request) string
}
func newOrgsAPI(s *Server) *orgsAPI {
return &orgsAPI{orgs: s.Orgs, identities: s.Identities, subjects: s.Subjects, memberIssuer: s.memberIssuer}
}
func (a *orgsAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/orgs", a.handleOrgsList)
mux.HandleFunc("POST /api/orgs", a.handleOrgCreate)
mux.HandleFunc("GET /api/orgs/{id}", a.handleOrgGet)
mux.HandleFunc("GET /api/orgs/{id}/workspaces", a.handleOrgWorkspacesList)
mux.HandleFunc("POST /api/orgs/{id}/workspaces", a.handleOrgWorkspaceCreate)
mux.HandleFunc("GET /api/orgs/{id}/members", a.handleOrgMembersList)
mux.HandleFunc("POST /api/orgs/{id}/members", a.handleOrgMemberAdd)
mux.HandleFunc("PUT /api/orgs/{id}/members/{identity}", a.handleOrgMemberSet)
mux.HandleFunc("DELETE /api/orgs/{id}/members/{identity}", a.handleOrgMemberRemove)
mux.HandleFunc("GET /api/orgs/{id}/agents", a.handleOrgAgentsList)
mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", instanceOnly(a.handleOrgAgentAssign))
}
// orgReady answers Unavailable when this process hosts no org store.
func (s *Server) orgReady(w http.ResponseWriter) bool {
if s.Orgs == nil {
func (a *orgsAPI) orgReady(w http.ResponseWriter) bool {
if a.orgs == nil {
http.Error(w, "orgs unavailable", http.StatusServiceUnavailable)
return false
}
@@ -23,7 +51,7 @@ func (s *Server) orgReady(w http.ResponseWriter) bool {
// orgInPath resolves the route's {id}: the caller's own org, or any org for
// an instance admin. Another tenant reads as not found rather than leaking.
func (s *Server) orgInPath(w http.ResponseWriter, r *http.Request) (org.OrgID, bool) {
func (a *orgsAPI) orgInPath(w http.ResponseWriter, r *http.Request) (org.OrgID, bool) {
id := org.OrgID(r.PathValue("id"))
if id != policyOrg(r) && !instanceOwner(r) {
http.Error(w, "org not found", http.StatusNotFound)
@@ -35,11 +63,11 @@ func (s *Server) orgInPath(w http.ResponseWriter, r *http.Request) (org.OrgID, b
// handleOrgsList lists every org to an instance admin and the caller's own
// and member orgs to anyone else, naming the org the caller acts in and the
// ones it may select.
func (s *Server) handleOrgsList(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
func (a *orgsAPI) handleOrgsList(w http.ResponseWriter, r *http.Request) {
if !a.orgReady(w) {
return
}
values, err := s.Orgs.ListOrgs(r.Context())
values, err := a.orgs.ListOrgs(r.Context())
if err != nil {
writeOrgError(w, err)
return
@@ -60,15 +88,15 @@ func (s *Server) handleOrgsList(w http.ResponseWriter, r *http.Request) {
// handleOrgCreate creates an org with its default workspace and first owner.
// Only an instance admin may.
func (s *Server) handleOrgCreate(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
func (a *orgsAPI) handleOrgCreate(w http.ResponseWriter, r *http.Request) {
if !a.orgReady(w) {
return
}
if !instanceOwner(r) {
http.Error(w, "only an instance admin creates orgs", http.StatusForbidden)
return
}
creator, ok := s.Orgs.(org.Creator)
creator, ok := a.orgs.(org.Creator)
if !ok {
http.Error(w, "org creation unavailable", http.StatusServiceUnavailable)
return
@@ -91,15 +119,15 @@ func (s *Server) handleOrgCreate(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{"org": created})
}
func (s *Server) handleOrgGet(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
func (a *orgsAPI) handleOrgGet(w http.ResponseWriter, r *http.Request) {
if !a.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
id, ok := a.orgInPath(w, r)
if !ok {
return
}
value, err := s.Orgs.GetOrg(r.Context(), id)
value, err := a.orgs.GetOrg(r.Context(), id)
if err != nil {
writeOrgError(w, err)
return
@@ -107,15 +135,15 @@ func (s *Server) handleOrgGet(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{"org": value})
}
func (s *Server) handleOrgWorkspacesList(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
func (a *orgsAPI) handleOrgWorkspacesList(w http.ResponseWriter, r *http.Request) {
if !a.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
id, ok := a.orgInPath(w, r)
if !ok {
return
}
values, err := s.Orgs.ListWorkspaces(r.Context(), id)
values, err := a.orgs.ListWorkspaces(r.Context(), id)
if err != nil {
writeOrgError(w, err)
return
@@ -126,11 +154,11 @@ func (s *Server) handleOrgWorkspacesList(w http.ResponseWriter, r *http.Request)
writeJSON(w, map[string]any{"workspaces": values})
}
func (s *Server) handleOrgWorkspaceCreate(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
func (a *orgsAPI) handleOrgWorkspaceCreate(w http.ResponseWriter, r *http.Request) {
if !a.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
id, ok := a.orgInPath(w, r)
if !ok {
return
}
@@ -143,7 +171,7 @@ func (s *Server) handleOrgWorkspaceCreate(w http.ResponseWriter, r *http.Request
http.Error(w, "invalid workspace: "+err.Error(), http.StatusBadRequest)
return
}
value, err := s.Orgs.CreateWorkspace(r.Context(), org.Workspace{
value, err := a.orgs.CreateWorkspace(r.Context(), org.Workspace{
ID: org.WorkspaceID(request.ID), OrgID: id, Name: request.Name, Environment: request.Environment,
})
if err != nil {
@@ -154,15 +182,15 @@ func (s *Server) handleOrgWorkspaceCreate(w http.ResponseWriter, r *http.Request
writeJSON(w, map[string]any{"workspace": value})
}
func (s *Server) handleOrgMembersList(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
func (a *orgsAPI) handleOrgMembersList(w http.ResponseWriter, r *http.Request) {
if !a.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
id, ok := a.orgInPath(w, r)
if !ok {
return
}
values, err := s.Orgs.ListMembers(r.Context(), id)
values, err := a.orgs.ListMembers(r.Context(), id)
if err != nil {
writeOrgError(w, err)
return
@@ -175,11 +203,11 @@ func (s *Server) handleOrgMembersList(w http.ResponseWriter, r *http.Request) {
// handleOrgMemberSet grants or moves one identity's role in the caller's org,
// or in one workspace when the body names one.
func (s *Server) handleOrgMemberSet(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
func (a *orgsAPI) handleOrgMemberSet(w http.ResponseWriter, r *http.Request) {
if !a.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
id, ok := a.orgInPath(w, r)
if !ok {
return
}
@@ -197,10 +225,10 @@ func (s *Server) handleOrgMemberSet(w http.ResponseWriter, r *http.Request) {
WorkspaceID: org.WorkspaceID(request.Workspace),
Role: org.Role(request.Role),
}
if !s.mayChangeMembership(w, r, membership, membership.Role) {
if !a.mayChangeMembership(w, r, membership, membership.Role) {
return
}
if err := s.Orgs.EnsureMembership(r.Context(), membership); err != nil {
if err := a.orgs.EnsureMembership(r.Context(), membership); err != nil {
writeOrgError(w, err)
return
}
@@ -211,23 +239,23 @@ func (s *Server) handleOrgMemberSet(w http.ResponseWriter, r *http.Request) {
// their email, creating the identity and binding it so that person's next
// sign-in resolves to it with this role. An already-bound subject keeps its
// identity and only gains the membership.
func (s *Server) handleOrgMemberAdd(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
func (a *orgsAPI) handleOrgMemberAdd(w http.ResponseWriter, r *http.Request) {
if !a.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
id, ok := a.orgInPath(w, r)
if !ok {
return
}
if s.Subjects == nil || s.Identities == nil || s.memberIssuer(r) == "" {
if a.subjects == nil || a.identities == nil || a.memberIssuer(r) == "" {
http.Error(w, "adding a person needs a configured identity provider", http.StatusServiceUnavailable)
return
}
request, bound, name, ok := s.decodeMemberAdd(w, r)
request, bound, name, ok := a.decodeMemberAdd(w, r)
if !ok {
return
}
existing, err := s.Subjects.ResolveSubject(r.Context(), bound)
existing, err := a.subjects.ResolveSubject(r.Context(), bound)
if err != nil && !errors.Is(err, identity.ErrNotFound) {
writeIdentityError(w, err)
return
@@ -243,13 +271,13 @@ func (s *Server) handleOrgMemberAdd(w http.ResponseWriter, r *http.Request) {
return
}
}
if !s.mayChangeMembership(w, r, membership, membership.Role) {
if !a.mayChangeMembership(w, r, membership, membership.Role) {
return
}
if unbound && !s.createBoundIdentity(w, r, membership.IdentityID, name, bound) {
if unbound && !a.createBoundIdentity(w, r, membership.IdentityID, name, bound) {
return
}
if err := s.Orgs.EnsureMembership(r.Context(), membership); err != nil {
if err := a.orgs.EnsureMembership(r.Context(), membership); err != nil {
writeOrgError(w, err)
return
}
@@ -268,7 +296,7 @@ type memberAddRequest struct {
// decodeMemberAdd reads and validates an add-member body, returning the
// provider subject it names and the display name to give a new identity. It
// has written the error when ok is false.
func (s *Server) decodeMemberAdd(w http.ResponseWriter, r *http.Request) (request memberAddRequest, bound identity.Subject, name string, ok bool) {
func (a *orgsAPI) decodeMemberAdd(w http.ResponseWriter, r *http.Request) (request memberAddRequest, bound identity.Subject, name string, ok bool) {
request, ok = decodeBody[memberAddRequest](w, r)
if !ok {
return
@@ -280,9 +308,9 @@ func (s *Server) decodeMemberAdd(w http.ResponseWriter, r *http.Request) (reques
http.Error(w, "give either a subject or an email", http.StatusBadRequest)
return request, bound, name, false
case subject != "":
bound, name = identity.Subject{Issuer: s.memberIssuer(r), Subject: subject}, cmp.Or(name, subject)
bound, name = identity.Subject{Issuer: a.memberIssuer(r), Subject: subject}, cmp.Or(name, subject)
default:
bound, name = identity.EmailSubject(s.memberIssuer(r), email), cmp.Or(name, email)
bound, name = identity.EmailSubject(a.memberIssuer(r), email), cmp.Or(name, email)
}
if err := org.Role(request.Role).Validate(); err != nil {
writeOrgError(w, err)
@@ -293,7 +321,7 @@ func (s *Server) decodeMemberAdd(w http.ResponseWriter, r *http.Request) (reques
// createBoundIdentity makes a user identity and binds subject to it, having
// written the error and returned false when either step fails.
func (s *Server) createBoundIdentity(w http.ResponseWriter, r *http.Request, id identity.IdentityID, name string, subject identity.Subject) bool {
func (a *orgsAPI) createBoundIdentity(w http.ResponseWriter, r *http.Request, id identity.IdentityID, name string, subject identity.Subject) bool {
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
@@ -301,10 +329,10 @@ func (s *Server) createBoundIdentity(w http.ResponseWriter, r *http.Request, id
}
value, err := identity.New(id, identity.KindUser, name)
if err == nil {
_, err = s.Identities.Create(r.Context(), value, audit)
_, err = a.identities.Create(r.Context(), value, audit)
}
if err == nil {
err = s.Subjects.BindSubject(r.Context(), id, subject, audit)
err = a.subjects.BindSubject(r.Context(), id, subject, audit)
}
if err != nil {
writeIdentityError(w, err)
@@ -313,11 +341,11 @@ func (s *Server) createBoundIdentity(w http.ResponseWriter, r *http.Request, id
return true
}
func (s *Server) handleOrgMemberRemove(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
func (a *orgsAPI) handleOrgMemberRemove(w http.ResponseWriter, r *http.Request) {
if !a.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
id, ok := a.orgInPath(w, r)
if !ok {
return
}
@@ -326,25 +354,25 @@ func (s *Server) handleOrgMemberRemove(w http.ResponseWriter, r *http.Request) {
OrgID: id,
WorkspaceID: org.WorkspaceID(r.URL.Query().Get("workspace")),
}
if !s.mayChangeMembership(w, r, membership, "") {
if !a.mayChangeMembership(w, r, membership, "") {
return
}
if err := s.Orgs.RemoveMembership(r.Context(), membership); err != nil {
if err := a.orgs.RemoveMembership(r.Context(), membership); err != nil {
writeOrgError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleOrgAgentAssign(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
func (a *orgsAPI) handleOrgAgentAssign(w http.ResponseWriter, r *http.Request) {
if !a.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
id, ok := a.orgInPath(w, r)
if !ok {
return
}
err := s.Orgs.AssignAgent(r.Context(), org.AgentAssignment{
err := a.orgs.AssignAgent(r.Context(), org.AgentAssignment{
IdentityID: identity.IdentityID(r.PathValue("identity")), OrgID: id,
})
if err != nil {
@@ -362,7 +390,7 @@ func (s *Server) handleOrgAgentAssign(w http.ResponseWriter, r *http.Request) {
// of the org: member management is an admin's grant, and without this an
// admin could make themselves owner -- and an owner of org-sys owns the
// instance.
func (s *Server) mayChangeMembership(w http.ResponseWriter, r *http.Request, target org.Membership, grant org.Role) bool {
func (a *orgsAPI) mayChangeMembership(w http.ResponseWriter, r *http.Request, target org.Membership, grant org.Role) bool {
principal, ok := access.PrincipalFromContext(r.Context())
if !ok {
principal = access.SharedTokenOwner()
@@ -372,7 +400,7 @@ func (s *Server) mayChangeMembership(w http.ResponseWriter, r *http.Request, tar
}
touchesOwner := grant == org.RoleOwner
if !touchesOwner {
members, err := s.Orgs.ListMembers(r.Context(), target.OrgID)
members, err := a.orgs.ListMembers(r.Context(), target.OrgID)
if err != nil {
writeOrgError(w, err)
return false
@@ -406,28 +434,15 @@ func writeOrgError(w http.ResponseWriter, err error) {
}
}
func (s *Server) memberIssuer(r *http.Request) string {
if store, ok := s.authenticationSettings(); ok {
value, err := store.AuthenticationSettings(r.Context())
if err != nil {
return ""
}
if value.PublicURL != "" {
return value.OIDCIssuer
}
}
return s.Issuer
}
func (s *Server) handleOrgAgentsList(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
func (a *orgsAPI) handleOrgAgentsList(w http.ResponseWriter, r *http.Request) {
if !a.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
id, ok := a.orgInPath(w, r)
if !ok {
return
}
reader, ok := s.Orgs.(org.AgentAssignments)
reader, ok := a.orgs.(org.AgentAssignments)
if !ok {
http.Error(w, "agent assignments unavailable", http.StatusServiceUnavailable)
return
@@ -438,12 +453,12 @@ func (s *Server) handleOrgAgentsList(w http.ResponseWriter, r *http.Request) {
return
}
agents := make([]identity.Identity, 0, len(values))
if s.Identities == nil {
if a.identities == nil {
http.Error(w, "identity authority unavailable", http.StatusServiceUnavailable)
return
}
for _, assignment := range values {
value, err := s.Identities.Get(r.Context(), assignment.IdentityID)
value, err := a.identities.Get(r.Context(), assignment.IdentityID)
if err != nil {
writeIdentityError(w, err)
return
@@ -117,17 +117,8 @@ func (f *fakeOrgs) AssignAgent(_ context.Context, value org.AgentAssignment) err
// the real server mounts.
func orgRoutes(s *Server) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/orgs", s.handleOrgsList)
mux.HandleFunc("POST /api/orgs", s.handleOrgCreate)
newOrgsAPI(s).register(mux)
mux.HandleFunc("PUT /api/orgs/current", s.handleOrgSelect)
mux.HandleFunc("GET /api/orgs/{id}", s.handleOrgGet)
mux.HandleFunc("GET /api/orgs/{id}/workspaces", s.handleOrgWorkspacesList)
mux.HandleFunc("POST /api/orgs/{id}/workspaces", s.handleOrgWorkspaceCreate)
mux.HandleFunc("GET /api/orgs/{id}/members", s.handleOrgMembersList)
mux.HandleFunc("POST /api/orgs/{id}/members", s.handleOrgMemberAdd)
mux.HandleFunc("PUT /api/orgs/{id}/members/{identity}", s.handleOrgMemberSet)
mux.HandleFunc("DELETE /api/orgs/{id}/members/{identity}", s.handleOrgMemberRemove)
mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", s.handleOrgAgentAssign)
return s.requireToken(s.authorize(mux))
}
@@ -16,15 +16,15 @@ const maxTokenNameLength = 40
// Personal API tokens belong to the signed-in person; the State Store acts
// on the principal the request carries, so these handlers name no one.
func (s *Server) handlePersonalTokensList(w http.ResponseWriter, r *http.Request) {
func (a *identitiesAPI) handlePersonalTokensList(w http.ResponseWriter, r *http.Request) {
if !personalTokenOwner(r) {
writeJSON(w, map[string]any{"tokens": []identity.PersonalToken{}, "available": false})
return
}
if !s.personalTokensReady(w, r) {
if !a.personalTokensReady(w, r) {
return
}
tokens, err := s.PersonalTokens.ListPersonalTokens(r.Context())
tokens, err := a.tokens.ListPersonalTokens(r.Context())
if err != nil {
writeIdentityError(w, err)
return
@@ -37,22 +37,43 @@ func (s *Server) handlePersonalTokensList(w http.ResponseWriter, r *http.Request
// handlePersonalTokenCreate makes a token here and sends only its hash to the
// State Store; the response is the one time the token is shown.
func (s *Server) handlePersonalTokenCreate(w http.ResponseWriter, r *http.Request) {
if !s.personalTokensReady(w, r) {
func (a *identitiesAPI) handlePersonalTokenCreate(w http.ResponseWriter, r *http.Request) {
if !a.personalTokensReady(w, r) {
return
}
name, expiresAt, ok := decodeTokenRequest(w, r)
if !ok {
return
}
raw, subject, err := identity.NewPersonalToken()
if err != nil {
http.Error(w, "cannot create token", http.StatusInternalServerError)
return
}
if err := a.tokens.AddPersonalToken(r.Context(), subject, name, expiresAt); err != nil {
writeIdentityError(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusCreated)
writeJSON(w, map[string]string{"id": subject.Subject, "token": raw})
}
// decodeTokenRequest reads a token request's name and lifetime, the shape the
// personal-token route and the per-identity token route share.
func decodeTokenRequest(w http.ResponseWriter, r *http.Request) (string, *time.Time, bool) {
var body struct {
Name string `json:"name"`
Days int `json:"days"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&body); err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return
return "", nil, false
}
name := strings.TrimSpace(body.Name)
if name == "" || utf8.RuneCountInString(name) > maxTokenNameLength {
http.Error(w, "Name a token in up to 40 characters.", http.StatusBadRequest)
return
return "", nil, false
}
var expiresAt *time.Time
switch body.Days {
@@ -62,27 +83,16 @@ func (s *Server) handlePersonalTokenCreate(w http.ResponseWriter, r *http.Reques
expiresAt = &t
default:
http.Error(w, "Lifetime is 7, 30 or 90 days, or none.", http.StatusBadRequest)
return
return "", nil, false
}
raw, subject, err := identity.NewPersonalToken()
if err != nil {
http.Error(w, "cannot create token", http.StatusInternalServerError)
return
}
if err := s.PersonalTokens.AddPersonalToken(r.Context(), subject, name, expiresAt); err != nil {
writeIdentityError(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusCreated)
writeJSON(w, map[string]string{"id": subject.Subject, "token": raw})
return name, expiresAt, true
}
func (s *Server) handlePersonalTokenRevoke(w http.ResponseWriter, r *http.Request) {
if !s.personalTokensReady(w, r) {
func (a *identitiesAPI) handlePersonalTokenRevoke(w http.ResponseWriter, r *http.Request) {
if !a.personalTokensReady(w, r) {
return
}
if err := s.PersonalTokens.RevokePersonalToken(r.Context(), r.PathValue("id")); err != nil {
if err := a.tokens.RevokePersonalToken(r.Context(), r.PathValue("id")); err != nil {
writeIdentityError(w, err)
return
}
@@ -94,13 +104,13 @@ func personalTokenOwner(r *http.Request) bool {
return ok && p.IdentityID != "" && p.IdentityID != identity.SystemID
}
func (s *Server) personalTokensReady(w http.ResponseWriter, r *http.Request) bool {
func (a *identitiesAPI) personalTokensReady(w http.ResponseWriter, r *http.Request) bool {
if !personalTokenOwner(r) {
http.Error(w, "Personal tokens need a signed-in person.", http.StatusForbidden)
return false
}
if s.PersonalTokens == nil {
if a.tokens == nil {
http.Error(w, "personal tokens unavailable", http.StatusServiceUnavailable)
return false
}
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"time"
@@ -79,15 +80,38 @@ func runView(r scheduling.Run) scheduleRunView {
}
}
func (s *Server) ownerView(ctx context.Context, owner scheduling.Owner, names map[org.OrgID]string) scheduleOwnerView {
// schedulesAPI owns the /api/schedules routes. They are org-scoped, not
// instance-only: the system org sees every schedule, any other org only its
// own, and the handlers enforce that ownership.
type schedulesAPI struct {
schedules ScheduleStore
orgs org.API
dispatches storecontract.DispatchLedger
log *slog.Logger
authorize func(http.ResponseWriter, *http.Request) bool
}
func newSchedulesAPI(s *Server) *schedulesAPI {
return &schedulesAPI{schedules: s.Schedules, orgs: s.Orgs, dispatches: s.Dispatches, log: s.Log, authorize: s.authorizeTaskMutation}
}
func (a *schedulesAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/schedules", a.handleSchedules)
mux.HandleFunc("PUT /api/schedules/{id}", a.handleSchedulePut)
mux.HandleFunc("DELETE /api/schedules/{id}", a.handleScheduleDelete)
mux.HandleFunc("GET /api/schedules/{id}/runs", a.handleScheduleRuns)
mux.HandleFunc("POST /api/schedules/{id}/runs", a.handleScheduleRunNow)
}
func (a *schedulesAPI) ownerView(ctx context.Context, owner scheduling.Owner, names map[org.OrgID]string) scheduleOwnerView {
view := scheduleOwnerView{Kind: owner.Kind, ID: owner.ID}
id := org.OrgID(owner.ID)
if owner.Kind == scheduling.OwnerInstance {
id = org.DefaultOrgID
}
name, ok := names[id]
if !ok && s.Orgs != nil {
if found, err := s.Orgs.GetOrg(ctx, id); err == nil {
if !ok && a.orgs != nil {
if found, err := a.orgs.GetOrg(ctx, id); err == nil {
name = found.Name
}
names[id] = name
@@ -96,9 +120,9 @@ func (s *Server) ownerView(ctx context.Context, owner scheduling.Owner, names ma
return view
}
func (s *Server) scheduleView(ctx context.Context, sched scheduling.Schedule, names map[org.OrgID]string) scheduleView {
func (a *schedulesAPI) scheduleView(ctx context.Context, sched scheduling.Schedule, names map[org.OrgID]string) scheduleView {
view := scheduleView{
ID: sched.ID, Name: sched.Name, Owner: s.ownerView(ctx, sched.Owner, names),
ID: sched.ID, Name: sched.Name, Owner: a.ownerView(ctx, sched.Owner, names),
Enabled: sched.Enabled, BuiltIn: sched.BuiltIn, Timing: sched.Timing,
NextRun: optionalTime(sched.NextRun),
}
@@ -109,7 +133,7 @@ func (s *Server) scheduleView(ctx context.Context, sched scheduling.Schedule, na
return view
}
func (s *Server) scheduleError(ctx context.Context, w http.ResponseWriter, op string, err error) {
func (a *schedulesAPI) scheduleError(ctx context.Context, w http.ResponseWriter, op string, err error) {
switch {
case errors.Is(err, scheduling.ErrNotFound):
http.Error(w, "schedule not found", http.StatusNotFound)
@@ -118,13 +142,13 @@ func (s *Server) scheduleError(ctx context.Context, w http.ResponseWriter, op st
case errors.Is(err, scheduling.ErrInvalidSpec):
http.Error(w, err.Error(), http.StatusBadRequest)
default:
s.Log.ErrorContext(ctx, op, "err", err)
a.log.ErrorContext(ctx, op, "err", err)
http.Error(w, op+" failed", http.StatusInternalServerError)
}
}
func (s *Server) schedulesReady(w http.ResponseWriter) bool {
if s.Schedules == nil {
func (a *schedulesAPI) schedulesReady(w http.ResponseWriter) bool {
if a.schedules == nil {
http.Error(w, "schedules unavailable", http.StatusServiceUnavailable)
return false
}
@@ -152,15 +176,15 @@ func scheduleOwned(instance bool, orgID org.OrgID, sched scheduling.Schedule) bo
// ownedSchedule reads the named schedule and reports whether the acting org
// owns it, answering not found when it does not exist or belongs elsewhere.
func (s *Server) ownedSchedule(w http.ResponseWriter, r *http.Request, id string) (scheduling.Schedule, bool) {
func (a *schedulesAPI) ownedSchedule(w http.ResponseWriter, r *http.Request, id string) (scheduling.Schedule, bool) {
orgID, instance := scheduleScope(r)
sched, err := s.Schedules.GetSchedule(r.Context(), id)
sched, err := a.schedules.GetSchedule(r.Context(), id)
switch {
case errors.Is(err, scheduling.ErrNotFound):
http.Error(w, "schedule not found", http.StatusNotFound)
return scheduling.Schedule{}, false
case err != nil:
s.scheduleError(r.Context(), w, "get schedule", err)
a.scheduleError(r.Context(), w, "get schedule", err)
return scheduling.Schedule{}, false
case !scheduleOwned(instance, orgID, sched):
http.Error(w, "schedule not found", http.StatusNotFound)
@@ -169,13 +193,13 @@ func (s *Server) ownedSchedule(w http.ResponseWriter, r *http.Request, id string
return sched, true
}
func (s *Server) handleSchedules(w http.ResponseWriter, r *http.Request) {
if !s.schedulesReady(w) {
func (a *schedulesAPI) handleSchedules(w http.ResponseWriter, r *http.Request) {
if !a.schedulesReady(w) {
return
}
list, err := s.Schedules.ListSchedules(r.Context())
list, err := a.schedules.ListSchedules(r.Context())
if err != nil {
s.scheduleError(r.Context(), w, "list schedules", err)
a.scheduleError(r.Context(), w, "list schedules", err)
return
}
orgID, instance := scheduleScope(r)
@@ -185,7 +209,7 @@ func (s *Server) handleSchedules(w http.ResponseWriter, r *http.Request) {
if !scheduleOwned(instance, orgID, sched) {
continue
}
views = append(views, s.scheduleView(r.Context(), sched, names))
views = append(views, a.scheduleView(r.Context(), sched, names))
}
writeJSON(w, map[string]any{"schedules": views})
}
@@ -194,8 +218,8 @@ func (s *Server) handleSchedules(w http.ResponseWriter, r *http.Request) {
// change on it. A new schedule belongs to the instance when the system org
// writes it and to the acting org otherwise; an existing schedule must be the
// acting org's own.
func (s *Server) handleSchedulePut(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) || !s.schedulesReady(w) {
func (a *schedulesAPI) handleSchedulePut(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) || !a.schedulesReady(w) {
return
}
var input scheduleInput
@@ -205,7 +229,7 @@ func (s *Server) handleSchedulePut(w http.ResponseWriter, r *http.Request) {
}
id := r.PathValue("id")
orgID, instance := scheduleScope(r)
sched, err := s.Schedules.GetSchedule(r.Context(), id)
sched, err := a.schedules.GetSchedule(r.Context(), id)
switch {
case errors.Is(err, scheduling.ErrNotFound):
owner := scheduling.Owner{Kind: scheduling.OwnerInstance}
@@ -214,45 +238,45 @@ func (s *Server) handleSchedulePut(w http.ResponseWriter, r *http.Request) {
}
sched = scheduling.Schedule{ID: id, Owner: owner}
case err != nil:
s.scheduleError(r.Context(), w, "get schedule", err)
a.scheduleError(r.Context(), w, "get schedule", err)
return
case !scheduleOwned(instance, orgID, sched):
http.Error(w, "schedule not found", http.StatusNotFound)
return
}
sched.Name, sched.Enabled, sched.Timing = input.Name, input.Enabled, input.Timing
saved, err := s.Schedules.PutSchedule(r.Context(), sched)
saved, err := a.schedules.PutSchedule(r.Context(), sched)
if err != nil {
s.scheduleError(r.Context(), w, "save schedule", err)
a.scheduleError(r.Context(), w, "save schedule", err)
return
}
writeJSON(w, s.scheduleView(r.Context(), saved, map[org.OrgID]string{}))
writeJSON(w, a.scheduleView(r.Context(), saved, map[org.OrgID]string{}))
}
func (s *Server) handleScheduleDelete(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) || !s.schedulesReady(w) {
func (a *schedulesAPI) handleScheduleDelete(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) || !a.schedulesReady(w) {
return
}
if _, ok := s.ownedSchedule(w, r, r.PathValue("id")); !ok {
if _, ok := a.ownedSchedule(w, r, r.PathValue("id")); !ok {
return
}
if err := s.Schedules.DeleteSchedule(r.Context(), r.PathValue("id")); err != nil {
s.scheduleError(r.Context(), w, "delete schedule", err)
if err := a.schedules.DeleteSchedule(r.Context(), r.PathValue("id")); err != nil {
a.scheduleError(r.Context(), w, "delete schedule", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleScheduleRunNow(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) || !s.schedulesReady(w) {
func (a *schedulesAPI) handleScheduleRunNow(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) || !a.schedulesReady(w) {
return
}
if _, ok := s.ownedSchedule(w, r, r.PathValue("id")); !ok {
if _, ok := a.ownedSchedule(w, r, r.PathValue("id")); !ok {
return
}
run, err := s.Schedules.RequestScheduleRun(r.Context(), r.PathValue("id"))
run, err := a.schedules.RequestScheduleRun(r.Context(), r.PathValue("id"))
if err != nil {
s.scheduleError(r.Context(), w, "run schedule", err)
a.scheduleError(r.Context(), w, "run schedule", err)
return
}
writeJSON(w, runView(run))
@@ -260,34 +284,34 @@ func (s *Server) handleScheduleRunNow(w http.ResponseWriter, r *http.Request) {
// handleScheduleRuns lists a schedule's runs, each with the tasks its firing
// started: the binding dispatches recorded against the run's capture.
func (s *Server) handleScheduleRuns(w http.ResponseWriter, r *http.Request) {
if !s.schedulesReady(w) {
func (a *schedulesAPI) handleScheduleRuns(w http.ResponseWriter, r *http.Request) {
if !a.schedulesReady(w) {
return
}
if _, ok := s.ownedSchedule(w, r, r.PathValue("id")); !ok {
if _, ok := a.ownedSchedule(w, r, r.PathValue("id")); !ok {
return
}
runs, err := s.Schedules.ListScheduleRuns(r.Context(), r.PathValue("id"), scheduleRunsShown)
runs, err := a.schedules.ListScheduleRuns(r.Context(), r.PathValue("id"), scheduleRunsShown)
if err != nil {
s.scheduleError(r.Context(), w, "list schedule runs", err)
a.scheduleError(r.Context(), w, "list schedule runs", err)
return
}
views := make([]scheduleRunView, 0, len(runs))
for _, run := range runs {
view := runView(run)
view.TaskIDs = s.runTasks(r.Context(), run.CaptureID)
view.TaskIDs = a.runTasks(r.Context(), run.CaptureID)
views = append(views, view)
}
writeJSON(w, map[string]any{"runs": views})
}
func (s *Server) runTasks(ctx context.Context, captureID string) []int64 {
if captureID == "" || s.Dispatches == nil {
func (a *schedulesAPI) runTasks(ctx context.Context, captureID string) []int64 {
if captureID == "" || a.dispatches == nil {
return nil
}
dispatches, err := s.Dispatches.ListDispatches(ctx, storecontract.DispatchFilter{CaptureID: captureID, Limit: 50})
dispatches, err := a.dispatches.ListDispatches(ctx, storecontract.DispatchFilter{CaptureID: captureID, Limit: 50})
if err != nil {
s.Log.WarnContext(ctx, "schedule run tasks unavailable", "capture", captureID, "err", err)
a.log.WarnContext(ctx, "schedule run tasks unavailable", "capture", captureID, "err", err)
return nil
}
var ids []int64
@@ -99,11 +99,7 @@ func orgSchedule(id, orgID string) scheduling.Schedule {
// wrappers the real server mounts.
func scheduleRoutes(s *Server) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/schedules", s.handleSchedules)
mux.HandleFunc("PUT /api/schedules/{id}", s.handleSchedulePut)
mux.HandleFunc("DELETE /api/schedules/{id}", s.handleScheduleDelete)
mux.HandleFunc("GET /api/schedules/{id}/runs", s.handleScheduleRuns)
mux.HandleFunc("POST /api/schedules/{id}/runs", s.handleScheduleRunNow)
newSchedulesAPI(s).register(mux)
return s.requireToken(s.authorize(mux))
}
+39 -118
View File
@@ -34,11 +34,6 @@ type Server struct {
Accounts identity.Accounts
accountRateLimit *ratelimit.Limiter
// chatAsks holds the chat questions waiting for the operator's answer.
chatAsks chatAsks
// chatFiles holds the downloads for files chat turns sent.
chatFiles chatFiles
Store storecontract.TaskStore
Log *slog.Logger
@@ -123,13 +118,6 @@ type Server struct {
// Audit is the org-scoped audit feed, behind the audit page and the live
// tail. Nil answers 503 on every audit route.
Audit audit.Store
// auditExportOnce initialises auditExportRate; auditExporting and its
// mutex admit one export per identity. An export is bounded by its
// explicit range, a five-minute deadline and a page cap (see api_audit.go).
auditExportOnce sync.Once
auditExportRate *ratelimit.Limiter
auditExportMu sync.Mutex
auditExporting map[string]bool
// now is the clock applyState reads staleness against. Nil means
// time.Now; tests set it to pin a record's age.
now func() time.Time
@@ -285,68 +273,44 @@ func (s *Server) Broadcast(e events.Event) {
func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/summary", s.handleSummary)
mux.HandleFunc("GET /api/setup", s.handleSetup)
mux.HandleFunc("GET /api/workflows", s.handleWorkflows)
mux.HandleFunc("PUT /api/workflows/{id}/enabled", s.handleWorkflowEnabled)
mux.HandleFunc("POST /api/work-requests", s.handleWorkRequest)
mux.HandleFunc("GET /api/repositories", s.handleRepositories)
newWorkflowsAPI(s).register(mux)
mux.HandleFunc("POST /api/control-plane/resources/repository-policies/check", s.handleRepositoryCheck)
mux.HandleFunc("GET /api/skills", instanceOnly(s.handleSkills))
mux.HandleFunc("GET /api/curators", instanceOnly(s.handleCurators))
mux.HandleFunc("GET /api/captures", s.handleCaptures)
// Schedule routes are org-scoped, not instance-only: the system org sees
// every schedule, any other org only its own, and the handlers enforce
// that ownership.
mux.HandleFunc("GET /api/schedules", s.handleSchedules)
mux.HandleFunc("PUT /api/schedules/{id}", s.handleSchedulePut)
mux.HandleFunc("DELETE /api/schedules/{id}", s.handleScheduleDelete)
mux.HandleFunc("GET /api/schedules/{id}/runs", s.handleScheduleRuns)
mux.HandleFunc("POST /api/schedules/{id}/runs", s.handleScheduleRunNow)
newSchedulesAPI(s).register(mux)
newAuditAPI(s).register(mux)
newAlertsAPI(s).register(mux)
mux.HandleFunc("GET /api/channels", instanceOnly(s.handleChannels))
mux.HandleFunc("POST /api/channels/{id}/reload", instanceOnly(s.handleChannelReload))
mux.HandleFunc("GET /api/version", s.handleVersion)
mux.HandleFunc("GET /api/capabilities", s.handleCapabilities)
mux.HandleFunc("GET /api/audit", s.handleAudit)
mux.HandleFunc("GET /api/audit/export", s.handleAuditExport)
mux.HandleFunc("GET /api/alerts", s.handleAlerts)
mux.HandleFunc("POST /api/alerts/{id}/dismiss", s.handleAlertDismiss)
}
func (s *Server) registerTaskRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/tasks", s.handleTasks)
mux.HandleFunc("GET /api/task-meta", s.handleTaskMeta)
mux.HandleFunc("POST /api/tasks/{id}/action", s.handleTaskAction)
mux.HandleFunc("GET /api/tasks/{id}", s.handleTask)
mux.HandleFunc("GET /api/tasks/{id}/attempts", s.handleTaskAttempts)
mux.HandleFunc("GET /api/tasks/{id}/changes", s.handleTaskChanges)
mux.HandleFunc("GET /api/tasks/{id}/debug", s.handleTaskDebug)
mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs)
mux.HandleFunc("GET /api/tasks/{id}/transcript", s.handleTaskTranscript)
mux.HandleFunc("GET /api/tasks/{id}/sandbox", s.handleTaskSandbox)
mux.HandleFunc("GET /api/tasks/{id}/logs/download", s.handleTaskLogDownload)
newTasksAPI(s).register(mux)
}
func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/event-types", s.handleEventTypes)
mux.HandleFunc("POST /api/event-types", s.handleEventTypeCreate)
mux.HandleFunc("PUT /api/event-types/{id}", s.handleEventTypeUpdate)
mux.HandleFunc("DELETE /api/event-types/{id}", s.handleEventTypeDelete)
mux.HandleFunc("GET /api/mappings", s.handleMappingsList)
mux.HandleFunc("POST /api/mappings", s.handleMappingCreate)
mux.HandleFunc("GET /api/mappings/{id}", s.handleMappingGet)
mux.HandleFunc("PATCH /api/mappings/{id}", s.handleMappingUpdate)
mux.HandleFunc("DELETE /api/mappings/{id}", s.handleMappingDelete)
mux.HandleFunc("POST /api/mappings/preview", s.handleMappingPreview)
mux.HandleFunc("GET /api/bindings", s.handleBindingsList)
mux.HandleFunc("POST /api/bindings", s.handleBindingCreate)
mux.HandleFunc("GET /api/bindings/{id}", s.handleBindingGet)
mux.HandleFunc("PATCH /api/bindings/{id}", s.handleBindingUpdate)
mux.HandleFunc("DELETE /api/bindings/{id}", s.handleBindingDelete)
mux.HandleFunc("POST /api/bindings/{id}/approve", s.handleBindingTransition("approve", storecontract.BindingStore.ApproveBinding))
mux.HandleFunc("POST /api/bindings/{id}/pause", s.handleBindingTransition("pause", storecontract.BindingStore.PauseBinding))
mux.HandleFunc("POST /api/bindings/{id}/resume", s.handleBindingTransition("resume", storecontract.BindingStore.ResumeBinding))
mux.HandleFunc("GET /api/bindings/{id}/dispatches", s.handleDispatches(func(id string) (storecontract.DispatchFilter, bool) {
return storecontract.DispatchFilter{BindingID: id}, id != ""
}))
// Event types register unconditionally: the list answers {"enabled": false}
// when the store is nil. Mappings and sources mount a 503 stub otherwise.
newEventTypesAPI(s).register(mux)
if s.Mappings == nil {
for _, p := range mappingsRoutes {
mux.HandleFunc(p, notConfigured("mappings not configured"))
}
} else {
newMappingsAPI(s).register(mux)
}
// The bindings module owns its routes and registers itself when the store
// is configured; the stub keeps the 503 "not configured" answers otherwise.
if s.Bindings == nil {
for _, p := range bindingsRoutes {
mux.HandleFunc(p, notConfigured("bindings not configured"))
}
} else {
newBindingsAPI(s).register(mux)
}
mux.HandleFunc("GET /api/captures/{id}/dispatches", s.handleDispatches(func(id string) (storecontract.DispatchFilter, bool) {
return storecontract.DispatchFilter{CaptureID: id}, id != ""
}))
@@ -354,79 +318,36 @@ func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
taskID, err := strconv.ParseInt(id, 10, 64)
return storecontract.DispatchFilter{TaskID: taskID}, err == nil && taskID > 0
}))
mux.HandleFunc("GET /api/sources", s.handleSourcesList)
mux.HandleFunc("POST /api/sources", s.handleSourceCreate)
mux.HandleFunc("POST /api/sources/{path}/signing", s.handleSourceSigning)
mux.HandleFunc("POST /api/sources/{path}/approve-unsigned", s.handleSourceApproveUnsigned)
mux.HandleFunc("POST /api/sources/{path}/secret", s.handleSourceSecret)
mux.HandleFunc("PUT /api/sources/{path}/name", s.handleSourceName)
mux.HandleFunc("PUT /api/sources/{path}/delivery-header", s.handleSourceDeliveryHeader)
mux.HandleFunc("DELETE /api/sources/{path}", s.handleSourceDelete)
if s.Sources == nil {
for _, p := range sourcesRoutes {
mux.HandleFunc(p, notConfigured("sources not configured"))
}
} else {
newSourcesAPI(s).register(mux)
}
}
func (s *Server) registerHarnessRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/harness/bindings", s.handleHarnessBindings)
mux.HandleFunc("GET /api/harness/terminal", s.handleHarnessTerminal)
newHarnessAPI(s).register(mux)
}
func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/extensions", s.handleExtensions)
mux.HandleFunc("POST /api/extensions", s.handleExtensionInstall)
mux.HandleFunc("GET /api/extensions/catalogue", s.handleCatalogue)
mux.HandleFunc("POST /api/extensions/catalogue/{name}/install", s.handleCatalogueInstall)
mux.HandleFunc("POST /api/extensions/{name}/accept", s.handleExtensionAccept)
mux.HandleFunc("POST /api/extensions/{name}/update", s.handleExtensionUpdate)
mux.HandleFunc("POST /api/extensions/{name}/approve-update", s.handleExtensionApproveUpdate)
mux.HandleFunc("POST /api/extensions/{name}/rollback", s.handleExtensionRollback)
mux.HandleFunc("PUT /api/extensions/{name}/update-policy", s.handleExtensionUpdatePolicy)
mux.HandleFunc("PUT /api/extensions/{name}/enabled", s.handleExtensionEnabled)
mux.HandleFunc("DELETE /api/extensions/{name}", s.handleExtensionRemove)
mux.HandleFunc("GET /api/control-plane/catalog", s.handleControlPlaneCatalog)
newExtensionsAPI(s).register(mux)
mux.HandleFunc("GET /api/control-plane/apply-status", instanceOnly(s.handleApplyStatus))
mux.HandleFunc("GET /api/services", instanceOnly(s.handleServices))
mux.HandleFunc("GET /api/access/policies", s.handleListPolicies)
mux.HandleFunc("PUT /api/access/policies", s.handlePutPolicy)
mux.HandleFunc("DELETE /api/access/policies", s.handleDeletePolicy)
mux.HandleFunc("GET /api/access/denials", s.handleListDenials)
mux.HandleFunc("GET /api/control-plane/resources/{kind}", s.handleControlPlaneQuery)
mux.HandleFunc("GET /api/control-plane/resources/{kind}/history", s.handleControlPlaneHistory)
mux.HandleFunc("POST /api/control-plane/resources/{kind}/commands/{command}", s.handleControlPlaneCommand)
mux.HandleFunc("GET /api/identities", instanceOnly(s.handleIdentitiesList))
mux.HandleFunc("GET /api/orgs", s.handleOrgsList)
mux.HandleFunc("POST /api/orgs", s.handleOrgCreate)
newAccessAPI(s).register(mux)
newControlPlaneAPI(s).register(mux)
newLogsAPI(s).register(mux)
newOrgsAPI(s).register(mux)
newIdentitiesAPI(s).register(mux)
mux.HandleFunc("PUT /api/orgs/current", s.handleOrgSelect)
mux.HandleFunc("GET /api/orgs/{id}", s.handleOrgGet)
mux.HandleFunc("GET /api/orgs/{id}/workspaces", s.handleOrgWorkspacesList)
mux.HandleFunc("POST /api/orgs/{id}/workspaces", s.handleOrgWorkspaceCreate)
mux.HandleFunc("GET /api/orgs/{id}/members", s.handleOrgMembersList)
mux.HandleFunc("POST /api/orgs/{id}/members", s.handleOrgMemberAdd)
mux.HandleFunc("PUT /api/orgs/{id}/members/{identity}", s.handleOrgMemberSet)
mux.HandleFunc("DELETE /api/orgs/{id}/members/{identity}", s.handleOrgMemberRemove)
mux.HandleFunc("GET /api/orgs/{id}/agents", s.handleOrgAgentsList)
mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", instanceOnly(s.handleOrgAgentAssign))
mux.HandleFunc("GET /api/tokens", s.handlePersonalTokensList)
mux.HandleFunc("POST /api/tokens", s.handlePersonalTokenCreate)
mux.HandleFunc("DELETE /api/tokens/{id}", s.handlePersonalTokenRevoke)
mux.HandleFunc("POST /api/identities", instanceOnly(s.handleIdentityCreate))
mux.HandleFunc("POST /api/identities/{id}/{command}", instanceOnly(s.handleIdentityCommand))
mux.HandleFunc("GET /api/config", instanceOnly(s.handleConfig))
mux.HandleFunc("GET /api/secret-engines", instanceOnly(s.handleSecretEngines))
mux.HandleFunc("POST /api/secret-references/check", instanceOnly(s.handleSecretCheck))
mux.HandleFunc("GET /api/logs", instanceOnly(s.handleLogs))
}
func (s *Server) registerChatRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/chat/sessions", s.handleChatSessions)
mux.HandleFunc("GET /api/chat/sessions/{id}/messages", s.handleChatMessages)
mux.HandleFunc("GET /api/chat/sessions/{id}/turns", s.handleChatTurns)
mux.HandleFunc("POST /api/chat/message", s.handleChatMessage)
mux.HandleFunc("POST /api/chat/stream", s.handleChatStream)
mux.HandleFunc("POST /api/chat/cancel", s.handleChatCancel)
mux.HandleFunc("POST /api/chat/answer", s.handleChatAnswer)
mux.HandleFunc("GET /api/chat/file/{token}", s.handleChatFile)
mux.HandleFunc("GET /api/chat/update", instanceOnly(s.handleChatUpdate))
mux.HandleFunc("POST /api/chat/update/defer", instanceOnly(s.handleChatUpdateDefer))
mux.HandleFunc("POST /api/chat/update/install", instanceOnly(s.handleChatUpdateInstall))
newChatAPI(s).register(mux)
}
func (s *Server) Handler() http.Handler {
+289
View File
@@ -0,0 +1,289 @@
package webui
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"slices"
"strings"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// sourcesAPI owns the /api/sources routes. Constructed only when the source
// store is configured; Server mounts a 503 stub otherwise.
type sourcesAPI struct {
sources storecontract.SourceStore
log *slog.Logger
authorize func(http.ResponseWriter, *http.Request) bool
authorizeCreateIn func(http.ResponseWriter, *http.Request, access.ResourceKind, org.WorkspaceID) bool
recentRefusals func(*http.Request) map[string]storecontract.CaptureRefusals
}
func newSourcesAPI(s *Server) *sourcesAPI {
return &sourcesAPI{
sources: s.Sources,
log: s.Log,
authorize: s.authorizeTaskMutation,
authorizeCreateIn: s.authorizeCreateIn,
recentRefusals: s.recentRefusals,
}
}
// sourcesRoutes lists the method+path patterns the sources module owns, so
// the 503 stub mounts exactly the same routes.
var sourcesRoutes = []string{
"GET /api/sources",
"POST /api/sources",
"POST /api/sources/{path}/signing",
"POST /api/sources/{path}/approve-unsigned",
"POST /api/sources/{path}/secret",
"PUT /api/sources/{path}/name",
"PUT /api/sources/{path}/delivery-header",
"DELETE /api/sources/{path}",
}
func (a *sourcesAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/sources", a.handleSourcesList)
mux.HandleFunc("POST /api/sources", a.handleSourceCreate)
mux.HandleFunc("POST /api/sources/{path}/signing", a.handleSourceSigning)
mux.HandleFunc("POST /api/sources/{path}/approve-unsigned", a.handleSourceApproveUnsigned)
mux.HandleFunc("POST /api/sources/{path}/secret", a.handleSourceSecret)
mux.HandleFunc("PUT /api/sources/{path}/name", a.handleSourceName)
mux.HandleFunc("PUT /api/sources/{path}/delivery-header", a.handleSourceDeliveryHeader)
mux.HandleFunc("DELETE /api/sources/{path}", a.handleSourceDelete)
}
func (a *sourcesAPI) handleSourcesList(w http.ResponseWriter, r *http.Request) {
if a.sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
list, err := a.sources.ListSources(r.Context())
if err != nil {
a.log.ErrorContext(r.Context(), "list sources", "err", err)
http.Error(w, "list sources failed", http.StatusInternalServerError)
return
}
list = slices.DeleteFunc(list, func(src source.Source) bool { return !listedIn(r, src.WorkspaceID) })
for i := range list {
list[i].Secret = ""
}
writeJSON(w, map[string]any{"sources": list, "refusals": a.recentRefusals(r)})
}
func (a *sourcesAPI) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if a.sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
var req struct {
Path string `json:"path"`
// Workspace is the caller's org workspace to create it in; empty is
// the default one.
Workspace org.WorkspaceID `json:"workspace"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
if !a.authorizeCreateIn(w, r, access.KindSource, req.Workspace) {
return
}
src, err := source.New(req.Path)
if errors.Is(err, source.ErrInvalidPath) || errors.Is(err, source.ErrReservedPath) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err == nil {
src.WorkspaceID = req.Workspace
err = a.sources.InsertSource(r.Context(), src)
}
if err != nil {
a.sourceError(w, "create source", err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, src)
}
// handleSourceSigning turns signing on at once, or requests turning it off.
func (a *sourcesAPI) handleSourceSigning(w http.ResponseWriter, r *http.Request) {
var req struct {
Signed bool `json:"signed"`
}
if !a.authorize(w, r) {
return
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
transition := (*source.Source).RequestUnsigned
if req.Signed {
transition = (*source.Source).RequireSigning
}
a.transitionSource(w, r, transition)
}
func (a *sourcesAPI) handleSourceApproveUnsigned(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
a.transitionSource(w, r, (*source.Source).ApproveUnsigned)
}
// transitionSource applies one domain signing transition and writes it with
// the state it was decided from, so a concurrent change is refused.
func (a *sourcesAPI) transitionSource(w http.ResponseWriter, r *http.Request, transition func(*source.Source) error) {
src, ok := a.loadSource(w, r)
if !ok {
return
}
from := src.Signing
if err := transition(src); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return
}
if err := a.sources.SetSourceSigning(r.Context(), src.Path, from, src.Signing); err != nil {
a.sourceError(w, "set source signing", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceSecret generates a new secret and returns it once.
func (a *sourcesAPI) handleSourceSecret(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
src, ok := a.loadSource(w, r)
if !ok {
return
}
secret, err := source.NewSecret()
if err == nil {
err = a.sources.SetSourceSecret(r.Context(), src.Path, secret)
}
if err != nil {
a.sourceError(w, "set source secret", err)
return
}
src.Secret = secret
writeJSON(w, src)
}
// handleSourceName relabels a source; its path does not change.
func (a *sourcesAPI) handleSourceName(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
src, ok := a.loadSource(w, r)
if !ok {
return
}
var request struct {
Name string `json:"name"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
http.Error(w, "invalid source name", http.StatusBadRequest)
return
}
src.Name = strings.TrimSpace(request.Name)
if err := a.sources.SetSourceName(r.Context(), src.Path, src.Name); err != nil {
a.sourceError(w, "set source name", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceDeliveryHeader sets the header that names a source's
// deliveries, so a sender's retry dispatches no second run.
func (a *sourcesAPI) handleSourceDeliveryHeader(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
src, ok := a.loadSource(w, r)
if !ok {
return
}
var request struct {
Header string `json:"header"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&request); err != nil {
http.Error(w, "invalid delivery header", http.StatusBadRequest)
return
}
header, err := source.DeliveryHeader(request.Header)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
src.DeliveryHeader = header
if err := a.sources.SetSourceDeliveryHeader(r.Context(), src.Path, header); err != nil {
a.sourceError(w, "set source delivery header", err)
return
}
src.Secret = ""
writeJSON(w, src)
}
// handleSourceDelete deletes a source no armed binding fires on.
func (a *sourcesAPI) handleSourceDelete(w http.ResponseWriter, r *http.Request) {
if !a.authorize(w, r) {
return
}
if a.sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return
}
if err := a.sources.DeleteSource(r.Context(), r.PathValue("path")); err != nil {
a.sourceError(w, "delete source", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (a *sourcesAPI) loadSource(w http.ResponseWriter, r *http.Request) (*source.Source, bool) {
if a.sources == nil {
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
return nil, false
}
src, err := a.sources.GetSource(r.Context(), r.PathValue("path"))
if err != nil {
a.sourceError(w, "get source", err)
return nil, false
}
if src == nil {
http.Error(w, "source not found", http.StatusNotFound)
return nil, false
}
return src, true
}
func (a *sourcesAPI) sourceError(w http.ResponseWriter, what string, err error) {
switch {
case errors.Is(err, storecontract.ErrSourcePathTaken):
http.Error(w, "source path already taken", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceSigningStale):
http.Error(w, "source signing changed; reload and retry", http.StatusConflict)
case errors.Is(err, storecontract.ErrSourceNotFound):
http.Error(w, "source not found", http.StatusNotFound)
case errors.Is(err, org.ErrInvalidWorkspace):
http.Error(w, "that workspace is not one of this org's", http.StatusBadRequest)
case errors.Is(err, storecontract.ErrSourceInUse):
http.Error(w, "an armed binding fires on this source; pause or delete it first", http.StatusConflict)
default:
a.log.Error(what, "err", err)
http.Error(w, what+" failed", http.StatusInternalServerError)
}
}
+63
View File
@@ -0,0 +1,63 @@
package webui
import (
"log/slog"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
// tasksAPI owns the /api/tasks routes and /api/task-meta. Optional
// dependencies (steps, taskLogs, sandbox, chat) stay nil-safe: each handler
// reports the feature unavailable rather than the module being absent.
type tasksAPI struct {
store storecontract.TaskStore
steps storecontract.StepReader
taskLogs TaskLogSource
sandbox SandboxView
chat *ChatService
log *slog.Logger
authorize func(http.ResponseWriter, *http.Request) bool
configSource func() ConfigViewSource
recovery func(*http.Request, *task.Task) *taskRecoveryView
}
func newTasksAPI(s *Server) *tasksAPI {
return &tasksAPI{
store: s.Store,
steps: s.Steps,
taskLogs: s.TaskLogs,
sandbox: s.SandboxView,
chat: s.Chat,
log: s.Log,
authorize: s.authorizeTaskMutation,
configSource: s.configSource,
recovery: s.taskRecovery,
}
}
func (a *tasksAPI) logf(msg string, args ...any) { warnf(a.log, msg, args...) }
// warnf logs at warn level and tolerates a nil logger, as tests construct
// servers without one.
func warnf(log *slog.Logger, msg string, args ...any) {
if log != nil {
log.Warn(msg, args...)
}
}
func (a *tasksAPI) register(mux *http.ServeMux) {
mux.HandleFunc("GET /api/tasks", a.handleTasks)
mux.HandleFunc("GET /api/task-meta", a.handleTaskMeta)
mux.HandleFunc("POST /api/tasks/{id}/action", a.handleTaskAction)
mux.HandleFunc("GET /api/tasks/{id}", a.handleTask)
mux.HandleFunc("GET /api/tasks/{id}/attempts", a.handleTaskAttempts)
mux.HandleFunc("GET /api/tasks/{id}/changes", a.handleTaskChanges)
mux.HandleFunc("GET /api/tasks/{id}/debug", a.handleTaskDebug)
mux.HandleFunc("GET /api/tasks/{id}/logs", a.handleTaskLogs)
mux.HandleFunc("GET /api/tasks/{id}/transcript", a.handleTaskTranscript)
mux.HandleFunc("GET /api/tasks/{id}/sandbox", a.handleTaskSandbox)
mux.HandleFunc("GET /api/tasks/{id}/logs/download", a.handleTaskLogDownload)
}
@@ -86,19 +86,19 @@ type taskAgentView struct {
// handleTaskAttempts returns a task's attempts from its events, each with the
// stages recorded as step executions.
func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) {
t, ok := s.taskByPathID(w, r)
func (a *tasksAPI) handleTaskAttempts(w http.ResponseWriter, r *http.Request) {
t, ok := a.taskByPathID(w, r)
if !ok {
return
}
evs, err := s.Store.TaskEvents(r.Context(), t.ID)
evs, err := a.store.TaskEvents(r.Context(), t.ID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var steps []task.StepExecution
if s.Steps != nil {
steps, err = s.Steps.ListSteps(r.Context(), t.ID, 0)
if a.steps != nil {
steps, err = a.steps.ListSteps(r.Context(), t.ID, 0)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@@ -117,7 +117,7 @@ func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) {
Inputs: t.Inputs,
Outputs: t.Outputs,
CalledBy: t.CallParentTaskID,
Recovery: s.taskRecovery(r, t),
Recovery: a.recovery(r, t),
})
}
@@ -125,13 +125,13 @@ func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) {
// request itself and reporting false when it cannot. An unknown task is 404
// plain text -- TaskByID says "no such row" the same way it says "here is the
// row", so the distinction is drawn here rather than leaked to the page.
func (s *Server) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Task, bool) {
func (a *tasksAPI) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Task, bool) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "bad id", http.StatusBadRequest)
return nil, false
}
t, err := s.Store.TaskByID(r.Context(), id)
t, err := a.store.TaskByID(r.Context(), id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil, false
@@ -145,8 +145,8 @@ func (s *Server) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Tas
// taskAttemptTarget resolves the task in {id} and the requested attempt,
// defaulting to the current one.
func (s *Server) taskAttemptTarget(w http.ResponseWriter, r *http.Request) (*task.Task, int, bool) {
t, ok := s.taskByPathID(w, r)
func (a *tasksAPI) taskAttemptTarget(w http.ResponseWriter, r *http.Request) (*task.Task, int, bool) {
t, ok := a.taskByPathID(w, r)
if !ok {
return nil, 0, false
}
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more