Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c42f64bfa | ||
|
|
d74216c6b7
|
||
|
|
0b7ce448ab
|
||
|
|
2fb8c09a00
|
||
|
|
0442f1849f
|
||
|
|
cf049797b0
|
||
|
|
18e6fe6af6
|
||
|
|
e8a84d3e41
|
||
|
|
c5f4541cbf
|
||
|
|
369e5038ca
|
||
|
|
66862a1bab
|
||
|
|
25dcdb2d19
|
||
|
|
1830a89898
|
||
|
|
6e718e165a
|
||
|
|
0a37b551f5
|
||
|
|
864b87faa6
|
||
|
|
d55d8580cf
|
||
|
|
63229d1711
|
No files matched your search
@@ -5,6 +5,12 @@ 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
|
||||
|
||||
+6
-4
@@ -101,11 +101,13 @@ target = "127.0.0.1:9090"
|
||||
# [[curators]]
|
||||
# name = "self-intake"
|
||||
# interval = "1h"
|
||||
# tools = ["run_list", "run_events"]
|
||||
# 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,
|
||||
# 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).
|
||||
# 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.
|
||||
@@ -52,7 +52,7 @@ listen = "127.0.0.1:8587"
|
||||
[[curators]]
|
||||
name = "self-intake"
|
||||
interval = "1h"
|
||||
tools = ["run_list", "run_events"]
|
||||
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, 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.
|
||||
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.
|
||||
"""
|
||||
@@ -90,6 +90,7 @@
|
||||
"/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/",
|
||||
@@ -195,6 +196,7 @@
|
||||
"/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/",
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
[
|
||||
{
|
||||
"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",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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{
|
||||
|
||||
@@ -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"
|
||||
@@ -112,6 +113,11 @@ func (b *server) registerWorkflowTools(ctx context.Context) {
|
||||
// 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)
|
||||
|
||||
@@ -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
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
File renamed without changes.
@@ -417,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
|
||||
}
|
||||
@@ -245,7 +245,7 @@ func TestIdentityTokenCreate(t *testing.T) {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.SetPathValue("id", tt.id)
|
||||
rec := httptest.NewRecorder()
|
||||
srv.handleIdentityTokenCreate(rec, req)
|
||||
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())
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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")
|
||||
@@ -260,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`) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -136,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
|
||||
}
|
||||
@@ -160,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)
|
||||
}
|
||||
}
|
||||
@@ -181,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
|
||||
}
|
||||
@@ -192,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
|
||||
}
|
||||
@@ -212,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
|
||||
}
|
||||
@@ -223,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
|
||||
}
|
||||
@@ -250,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 {
|
||||
@@ -300,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
|
||||
}
|
||||
@@ -398,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
|
||||
}
|
||||
@@ -434,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 {
|
||||
@@ -454,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
|
||||
}
|
||||
@@ -478,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
|
||||
}
|
||||
@@ -500,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
|
||||
}
|
||||
@@ -533,8 +562,8 @@ func updateStateDir() string {
|
||||
return configuration.UpdateStateDir()
|
||||
}
|
||||
|
||||
func (s *Server) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
func (a *chatAPI) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := a.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -554,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
|
||||
}
|
||||
@@ -592,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)
|
||||
@@ -618,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)})
|
||||
@@ -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
|
||||
}
|
||||
@@ -19,6 +19,27 @@ import (
|
||||
// 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
|
||||
}
|
||||
@@ -32,12 +53,12 @@ type identityRequest struct {
|
||||
ExpectedVersion int64 `json:"expected_version"`
|
||||
}
|
||||
|
||||
func (s *Server) handleIdentitiesList(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Identities == nil {
|
||||
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 := s.Identities.List(r.Context())
|
||||
values, err := a.identities.List(r.Context())
|
||||
if err != nil {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
@@ -48,7 +69,7 @@ func (s *Server) handleIdentitiesList(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{"identities": values})
|
||||
}
|
||||
|
||||
func (s *Server) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *identitiesAPI) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
|
||||
request, ok := decodeBody[identityRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
@@ -65,7 +86,7 @@ func (s *Server) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
value, err := identity.New(id, request.Kind, request.DisplayName)
|
||||
if err == nil {
|
||||
value, err = s.Identities.Create(r.Context(), value, audit)
|
||||
value, err = a.identities.Create(r.Context(), value, audit)
|
||||
}
|
||||
if err != nil {
|
||||
writeIdentityError(w, err)
|
||||
@@ -75,7 +96,7 @@ func (s *Server) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, value)
|
||||
}
|
||||
|
||||
func (s *Server) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *identitiesAPI) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
|
||||
request, ok := decodeBody[identityRequest](w, r)
|
||||
if !ok {
|
||||
return
|
||||
@@ -86,7 +107,7 @@ func (s *Server) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
|
||||
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)
|
||||
value, err := a.identities.Apply(r.Context(), identity.IdentityID(r.PathValue("id")), request.ExpectedVersion, command, audit)
|
||||
if err != nil {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
@@ -98,13 +119,13 @@ func (s *Server) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
|
||||
// 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 (s *Server) handleIdentityTokenCreate(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *identitiesAPI) handleIdentityTokenCreate(w http.ResponseWriter, r *http.Request) {
|
||||
id := identity.IdentityID(r.PathValue("id"))
|
||||
if s.Identities == nil {
|
||||
if a.identities == nil {
|
||||
http.Error(w, "identity store unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
value, err := s.Identities.Get(r.Context(), id)
|
||||
value, err := a.identities.Get(r.Context(), id)
|
||||
if errors.Is(err, identity.ErrNotFound) {
|
||||
http.Error(w, "No such identity.", http.StatusBadRequest)
|
||||
return
|
||||
@@ -123,7 +144,7 @@ func (s *Server) handleIdentityTokenCreate(w http.ResponseWriter, r *http.Reques
|
||||
}
|
||||
// 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 := s.PersonalTokens.(identityTokenBinder)
|
||||
binder, ok := a.tokens.(identityTokenBinder)
|
||||
if !ok {
|
||||
http.Error(w, "identity token binding unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -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,8 +37,8 @@ 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)
|
||||
@@ -50,7 +50,7 @@ func (s *Server) handlePersonalTokenCreate(w http.ResponseWriter, r *http.Reques
|
||||
http.Error(w, "cannot create token", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if err := s.PersonalTokens.AddPersonalToken(r.Context(), subject, name, expiresAt); err != nil {
|
||||
if err := a.tokens.AddPersonalToken(r.Context(), subject, name, expiresAt); err != nil {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -88,11 +88,11 @@ func decodeTokenRequest(w http.ResponseWriter, r *http.Request) (string, *time.T
|
||||
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
|
||||
}
|
||||
@@ -104,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
-119
@@ -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,80 +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("POST /api/identities/{id}/tokens", instanceOnly(s.handleIdentityTokenCreate))
|
||||
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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
File renamed without changes.
@@ -100,12 +100,12 @@ func structKeys(t reflect.Type) map[string]struct{} {
|
||||
}
|
||||
|
||||
// handleTaskChanges serves the changed files one attempt produced.
|
||||
func (s *Server) handleTaskChanges(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
func (a *tasksAPI) handleTaskChanges(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := a.taskAttemptTarget(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
|
||||
@@ -116,7 +116,7 @@ func (s *Server) handleTaskChanges(w http.ResponseWriter, r *http.Request) {
|
||||
// re-derived: the capture's own owner/repo/pr decide the URL, so a capture
|
||||
// taken before the PR existed has no pull-request link instead of one
|
||||
// pointing at a later attempt's PR.
|
||||
forge := s.resolveForge(r.Context())
|
||||
forge := a.resolveForge(r.Context())
|
||||
for i := range captures {
|
||||
target := task.Task{
|
||||
Owner: captures[i].Owner, Repo: captures[i].Repo,
|
||||
@@ -18,12 +18,12 @@ type taskDebugView struct {
|
||||
|
||||
// handleTaskDebug serves the task's raw record together with its whole event
|
||||
// list, for whichever attempt the request names.
|
||||
func (s *Server) handleTaskDebug(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
func (a *tasksAPI) handleTaskDebug(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := a.taskAttemptTarget(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
|
||||
@@ -67,13 +67,13 @@ func needsAttentionStatuses() []string {
|
||||
// narrows it (needs_attention is the grouped filter), ?limit sizes it, and ?cursor
|
||||
// resumes after the previous page; a full page answers the next cursor in the
|
||||
// X-Next-Cursor header.
|
||||
func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *tasksAPI) handleTasks(w http.ResponseWriter, r *http.Request) {
|
||||
page, err := taskPageFrom(r.URL.Query())
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
tasks, err := s.Store.TasksPage(r.Context(), page)
|
||||
tasks, err := a.store.TasksPage(r.Context(), page)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -82,11 +82,11 @@ func (s *Server) handleTasks(w http.ResponseWriter, r *http.Request) {
|
||||
last := tasks[len(tasks)-1]
|
||||
w.Header().Set("X-Next-Cursor", fmt.Sprintf("%d.%d", last.UpdatedAt.UnixNano(), last.ID))
|
||||
}
|
||||
forge := s.resolveForge(r.Context())
|
||||
forge := a.resolveForge(r.Context())
|
||||
views := make([]taskView, len(tasks))
|
||||
for i := range tasks {
|
||||
repoURL, issueURL, prURL := taskURLs(tasks[i], forge(tasks[i]))
|
||||
views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status), Approval: taskstate.ApprovalKind(tasks[i].Status, tasks[i].ReviewGate), RepoURL: repoURL, IssueURL: issueURL, PRURL: prURL, Recovery: s.taskRecovery(r, &tasks[i])}
|
||||
views[i] = taskView{Task: tasks[i], Actions: taskstate.Actions(tasks[i].Status), Approval: taskstate.ApprovalKind(tasks[i].Status, tasks[i].ReviewGate), RepoURL: repoURL, IssueURL: issueURL, PRURL: prURL, Recovery: a.recovery(r, &tasks[i])}
|
||||
}
|
||||
writeJSON(w, views)
|
||||
}
|
||||
@@ -144,9 +144,9 @@ type forgeCoordinates struct {
|
||||
// resolveForge returns a function mapping a task to the instance forge. A
|
||||
// multi-identity install withholds links: its tasks reach forges through
|
||||
// organisation connections this projection does not carry.
|
||||
func (s *Server) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates {
|
||||
func (a *tasksAPI) resolveForge(ctx context.Context) func(task.Task) forgeCoordinates {
|
||||
unlinked := func(task.Task) forgeCoordinates { return forgeCoordinates{} }
|
||||
view, ok, err := s.configSource()(ctx)
|
||||
view, ok, err := a.configSource()(ctx)
|
||||
if err != nil || !ok || view.MultiIdentity {
|
||||
return unlinked
|
||||
}
|
||||
@@ -172,13 +172,13 @@ func taskURLs(task task.Task, forge forgeCoordinates) (repoURL, issueURL, prURL
|
||||
return repoURL, issueURL, prURL
|
||||
}
|
||||
|
||||
func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *tasksAPI) handleTask(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "bad id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
evs, err := s.Store.TaskEvents(r.Context(), id)
|
||||
evs, err := a.store.TaskEvents(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -206,8 +206,8 @@ type taskActionRequest struct {
|
||||
CurrentDefinition bool `json:"current_definition"`
|
||||
}
|
||||
|
||||
func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
func (a *tasksAPI) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
@@ -219,7 +219,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := s.applyOperatorTaskAction(r.Context(), id, action, res); err != nil {
|
||||
if err := a.applyOperatorTaskAction(r.Context(), id, action, res); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, taskactions.ErrNotFound):
|
||||
http.Error(w, "task not found", http.StatusNotFound)
|
||||
@@ -229,7 +229,7 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
case errors.Is(err, taskactions.ErrUnavailable):
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
default:
|
||||
s.logf("task action failed", "task", id, "err", err)
|
||||
a.logf("task action failed", "task", id, "err", err)
|
||||
http.Error(w, "task action failed", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
@@ -348,8 +348,8 @@ func validOrigin(u *url.URL, wantScheme, wantHost string) bool {
|
||||
}
|
||||
|
||||
// applyOperatorTaskAction sends an operator's task action to the Gateway.
|
||||
func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action, res taskactions.ActionPayload) error {
|
||||
if s.Chat == nil || s.Chat.Contract == nil {
|
||||
func (a *tasksAPI) applyOperatorTaskAction(ctx context.Context, id int64, action taskstate.Action, res taskactions.ActionPayload) error {
|
||||
if a.chat == nil || a.chat.Contract == nil {
|
||||
return fmt.Errorf("%w: no gateway contract is wired", taskactions.ErrUnavailable)
|
||||
}
|
||||
// The actor comes from the credential the middleware resolved and never from
|
||||
@@ -360,7 +360,7 @@ func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action t
|
||||
if value, ok := ActingIdentity(ctx); ok {
|
||||
actor = taskactions.ActorFor(value)
|
||||
}
|
||||
_, err := s.Chat.Contract.ApplyOperatorTaskAction(ctx, actor, id, action, res)
|
||||
_, err := a.chat.Contract.ApplyOperatorTaskAction(ctx, actor, id, action, res)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -14,12 +14,12 @@ import (
|
||||
|
||||
// handleTaskLogs serves one attempt's log history, defaulting to the current
|
||||
// attempt. No reader reports disabled; no log file reports found=false.
|
||||
func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) {
|
||||
id, attempt, ok := s.taskLogTarget(w, r)
|
||||
func (a *tasksAPI) handleTaskLogs(w http.ResponseWriter, r *http.Request) {
|
||||
id, attempt, ok := a.taskLogTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
reader := s.taskLogReader()
|
||||
reader := a.taskLogs
|
||||
if reader == nil {
|
||||
writeDisabledTaskLogs(w, attempt)
|
||||
return
|
||||
@@ -83,12 +83,12 @@ func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// handleTaskLogDownload serves one attempt's raw log as a download. No reader
|
||||
// answers 503.
|
||||
func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) {
|
||||
id, attempt, ok := s.taskLogTarget(w, r)
|
||||
func (a *tasksAPI) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) {
|
||||
id, attempt, ok := a.taskLogTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
reader := s.taskLogReader()
|
||||
reader := a.taskLogs
|
||||
if reader == nil {
|
||||
http.Error(w, logging.ErrTaskLogsUnavailable.Error(), http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -114,7 +114,7 @@ func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) {
|
||||
// Once a 200 and a body are on the wire there is no status left to
|
||||
// send, so a failure partway through is logged where an operator can
|
||||
// find it rather than silently truncating the file.
|
||||
s.logf("task log download failed", "task", id, "attempt", attempt, "err", err)
|
||||
a.logf("task log download failed", "task", id, "attempt", attempt, "err", err)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
@@ -125,8 +125,8 @@ func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// taskLogTarget resolves the task and attempt for a log read, answering the
|
||||
// request itself on failure.
|
||||
func (s *Server) taskLogTarget(w http.ResponseWriter, r *http.Request) (id int64, attempt int, ok bool) {
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
func (a *tasksAPI) taskLogTarget(w http.ResponseWriter, r *http.Request) (id int64, attempt int, ok bool) {
|
||||
t, attempt, ok := a.taskAttemptTarget(w, r)
|
||||
if !ok {
|
||||
return 0, 0, false
|
||||
}
|
||||
@@ -206,14 +206,6 @@ func taskLogFilename(taskID int64, attempt int) string {
|
||||
return "task-" + strconv.FormatInt(taskID, 10) + "-attempt-" + strconv.Itoa(attempt) + ".log"
|
||||
}
|
||||
|
||||
// taskLogReader returns this process's task-log reader, or nil.
|
||||
func (s *Server) taskLogReader() TaskLogSource {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return s.TaskLogs
|
||||
}
|
||||
|
||||
// TaskLogSource is the read seam the task-log handlers consume. It is the
|
||||
// logging package's own reader contract, so a registry and a remote client
|
||||
// satisfy it without either one restating the log format -- the package that
|
||||
@@ -47,6 +47,6 @@ func buildTaskMeta() taskMetaView {
|
||||
}
|
||||
|
||||
// handleTaskMeta serves the catalog. See buildTaskMeta for what it carries.
|
||||
func (s *Server) handleTaskMeta(w http.ResponseWriter, _ *http.Request) {
|
||||
func (a *tasksAPI) handleTaskMeta(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, buildTaskMeta())
|
||||
}
|
||||
@@ -24,8 +24,8 @@ type SandboxView interface {
|
||||
// handleTaskSandbox streams a running attempt's sandbox output to a WebSocket.
|
||||
// Reading it is the same authority as reading the task's log, decided before
|
||||
// this handler runs. Input from the browser is discarded: a view has no stdin.
|
||||
func (s *Server) handleTaskSandbox(w http.ResponseWriter, r *http.Request) {
|
||||
if s.SandboxView == nil {
|
||||
func (a *tasksAPI) handleTaskSandbox(w http.ResponseWriter, r *http.Request) {
|
||||
if a.sandbox == nil {
|
||||
http.Error(w, "sandbox view not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func (s *Server) handleTaskSandbox(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "websocket upgrade required", http.StatusUpgradeRequired)
|
||||
return
|
||||
}
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
t, attempt, ok := a.taskAttemptTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -46,9 +46,9 @@ func (s *Server) handleTaskSandbox(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithCancel(ws.Request().Context())
|
||||
defer cancel()
|
||||
go func() { _, _ = io.Copy(io.Discard, ws); cancel() }()
|
||||
view, err := s.SandboxView.OpenRun(ctx, string(org.OrgFromContext(ws.Request().Context())), t.ID, int64(attempt))
|
||||
view, err := a.sandbox.OpenRun(ctx, string(org.OrgFromContext(ws.Request().Context())), t.ID, int64(attempt))
|
||||
if err != nil {
|
||||
s.logf("open sandbox view", "err", err, "task", t.ID, "attempt", attempt)
|
||||
a.logf("open sandbox view", "err", err, "task", t.ID, "attempt", attempt)
|
||||
_, _ = io.WriteString(ws, sandboxRefusal(err))
|
||||
return
|
||||
}
|
||||
@@ -45,8 +45,9 @@ func TestSandboxStreamLifetime(t *testing.T) {
|
||||
pr, pw := io.Pipe()
|
||||
view := &sandboxStream{PipeReader: pr, closed: make(chan struct{})}
|
||||
s := &Server{Store: sandboxTasks{}, SandboxView: view}
|
||||
a := newTasksAPI(s)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/tasks/{id}/sandbox", s.handleTaskSandbox)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/sandbox", a.handleTaskSandbox)
|
||||
server := httptest.NewServer(mux)
|
||||
defer server.Close()
|
||||
defer view.Close()
|
||||
File renamed without changes.
@@ -14,12 +14,12 @@ type taskTranscriptView struct {
|
||||
Entries []events.Event `json:"entries"`
|
||||
}
|
||||
|
||||
func (s *Server) handleTaskTranscript(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := s.taskAttemptTarget(w, r)
|
||||
func (a *tasksAPI) handleTaskTranscript(w http.ResponseWriter, r *http.Request) {
|
||||
t, attempt, ok := a.taskAttemptTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
entries, err := s.Store.TaskTranscript(r.Context(), t.ID, attempt)
|
||||
entries, err := a.store.TaskTranscript(r.Context(), t.ID, attempt)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -15,11 +15,11 @@ const workflowEnablementKind = "workflow-enablement"
|
||||
|
||||
// workflowEnablement returns which workflows each org has disabled, and the
|
||||
// resource version a replacement must name.
|
||||
func (s *Server) workflowEnablement(ctx context.Context) (task.WorkflowEnablement, int64, error) {
|
||||
if s.ControlPlane == nil {
|
||||
func (a *workflowsAPI) workflowEnablement(ctx context.Context) (task.WorkflowEnablement, int64, error) {
|
||||
if a.controlPlane == nil {
|
||||
return task.WorkflowEnablement{}, 0, nil
|
||||
}
|
||||
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowEnablementKind})
|
||||
response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowEnablementKind})
|
||||
if err != nil {
|
||||
return task.WorkflowEnablement{}, 0, err
|
||||
}
|
||||
@@ -39,11 +39,11 @@ type workflowEnabledRequest struct {
|
||||
|
||||
// handleWorkflowEnabled enables or disables a workflow for the caller's org
|
||||
// (org.OrgFromContext).
|
||||
func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
func (a *workflowsAPI) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
if s.ControlPlane == nil {
|
||||
if a.controlPlane == nil {
|
||||
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
found, err := s.hasWorkflowDefinition(r.Context(), id)
|
||||
found, err := a.hasWorkflowDefinition(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -61,7 +61,7 @@ func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "workflow not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
enablement, version, err := s.workflowEnablement(r.Context())
|
||||
enablement, version, err := a.workflowEnablement(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -76,7 +76,7 @@ func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if _, err := s.ControlPlane.Command(r.Context(), &controlpb.CommandRequest{
|
||||
if _, err := a.controlPlane.Command(r.Context(), &controlpb.CommandRequest{
|
||||
Kind: workflowEnablementKind, Command: "replace", ValueJson: value,
|
||||
ExpectedVersion: version, Actor: string(audit.ActorID),
|
||||
Source: audit.Source, RequestId: audit.RequestID,
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
@@ -17,6 +18,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/org"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
@@ -24,22 +26,46 @@ import (
|
||||
|
||||
const workflowDefinitionsKind = "workflow-definitions"
|
||||
|
||||
// workflowsAPI owns the workflow catalogue, per-org enablement, the
|
||||
// repository list and manual work requests. Its definition readers also back
|
||||
// the bindings and audit modules.
|
||||
type workflowsAPI struct {
|
||||
controlPlane controlpb.ControlPlaneServiceClient
|
||||
store storecontract.TaskStore
|
||||
log *slog.Logger
|
||||
emit func(context.Context, events.Event)
|
||||
authorize func(http.ResponseWriter, *http.Request) bool
|
||||
}
|
||||
|
||||
func newWorkflowsAPI(s *Server) *workflowsAPI {
|
||||
return &workflowsAPI{controlPlane: s.ControlPlane, store: s.Store, log: s.Log, emit: s.emit, authorize: s.authorizeTaskMutation}
|
||||
}
|
||||
|
||||
func (a *workflowsAPI) logf(msg string, args ...any) { warnf(a.log, msg, args...) }
|
||||
|
||||
func (a *workflowsAPI) register(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/workflows", a.handleWorkflows)
|
||||
mux.HandleFunc("PUT /api/workflows/{id}/enabled", a.handleWorkflowEnabled)
|
||||
mux.HandleFunc("POST /api/work-requests", a.handleWorkRequest)
|
||||
mux.HandleFunc("GET /api/repositories", a.handleRepositories)
|
||||
}
|
||||
|
||||
// handleWorkflows returns per-workflow and per-stage statistics: run counts,
|
||||
// outcome breakdowns and spend per workflow, plus duration and failure counts
|
||||
// per stage -- "where does it get stuck" for the workflows page.
|
||||
func (s *Server) handleWorkflows(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *workflowsAPI) handleWorkflows(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
workflows, err := s.Store.WorkflowStats(ctx)
|
||||
workflows, err := a.store.WorkflowStats(ctx)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
stages, err := s.Store.StageStats(ctx)
|
||||
stages, err := a.store.StageStats(ctx)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
definitions, err := s.workflowDefinitions(ctx)
|
||||
definitions, err := a.workflowDefinitions(ctx)
|
||||
if err != nil {
|
||||
http.Error(w, "workflow definitions unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -67,8 +93,8 @@ type workRequest struct {
|
||||
Draft string `json:"draft"`
|
||||
}
|
||||
|
||||
func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
func (a *workflowsAPI) handleWorkRequest(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.authorize(w, r) {
|
||||
return
|
||||
}
|
||||
principal, ok := access.PrincipalFromContext(r.Context())
|
||||
@@ -104,7 +130,7 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "title must be 80 characters or fewer; put details in instructions", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
iface, code, err := s.workRequestInterface(r.Context(), request)
|
||||
iface, code, err := a.workRequestInterface(r.Context(), request)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), code)
|
||||
return
|
||||
@@ -113,18 +139,18 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
owner, repo, status, err := s.workRequestRepository(r.Context(), iface.RepositoryMode(), request.Repository)
|
||||
owner, repo, status, err := a.workRequestRepository(r.Context(), iface.RepositoryMode(), request.Repository)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), status)
|
||||
return
|
||||
}
|
||||
created, err := s.Store.EnqueueChatTask(r.Context(), owner, repo, request.Title, request.Instructions, request.Workflow, string(principal.IdentityID), "", request.Draft, request.Inputs)
|
||||
created, err := a.store.EnqueueChatTask(r.Context(), owner, repo, request.Title, request.Instructions, request.Workflow, string(principal.IdentityID), "", request.Draft, request.Inputs)
|
||||
if err != nil {
|
||||
s.logf("work request enqueue failed", "err", err)
|
||||
a.logf("work request enqueue failed", "err", err)
|
||||
http.Error(w, "work request rejected", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
s.emit(r.Context(), events.Event{Kind: events.KindWorkRequestSubmitted, TaskID: created.ID, Repo: request.Repository, Workflow: request.Workflow, Detail: request.Title})
|
||||
a.emit(r.Context(), events.Event{Kind: events.KindWorkRequestSubmitted, TaskID: created.ID, Repo: request.Repository, Workflow: request.Workflow, Detail: request.Title})
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, map[string]any{"ok": true, "task_id": created.ID})
|
||||
}
|
||||
@@ -132,26 +158,26 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) {
|
||||
// workRequestInterface returns the interface a request runs against: the
|
||||
// draft's when it carries one, else the stored definition's. The workflow must
|
||||
// be defined and enabled either way.
|
||||
func (s *Server) workRequestInterface(ctx context.Context, request workRequest) (task.WorkflowInterface, int, error) {
|
||||
iface, enabled, err := s.enabledWorkflowInterface(ctx, request.Workflow)
|
||||
func (a *workflowsAPI) workRequestInterface(ctx context.Context, request workRequest) (task.WorkflowInterface, int, error) {
|
||||
iface, enabled, err := a.enabledWorkflowInterface(ctx, request.Workflow)
|
||||
switch {
|
||||
case err != nil:
|
||||
return iface, http.StatusServiceUnavailable, errors.New("workflow definitions unavailable")
|
||||
case !enabled:
|
||||
return iface, http.StatusConflict, errors.New("workflow is not enabled")
|
||||
case request.Draft != "":
|
||||
return s.checkDraft(ctx, request.Workflow, request.Draft)
|
||||
return a.checkDraft(ctx, request.Workflow, request.Draft)
|
||||
}
|
||||
return iface, 0, nil
|
||||
}
|
||||
|
||||
// checkDraft refuses a draft a save of the same document would refuse, and
|
||||
// returns the interface the draft declares.
|
||||
func (s *Server) checkDraft(ctx context.Context, id, draft string) (task.WorkflowInterface, int, error) {
|
||||
func (a *workflowsAPI) checkDraft(ctx context.Context, id, draft string) (task.WorkflowInterface, int, error) {
|
||||
if declared, err := workflow.DefinitionID(draft); err != nil || declared != id {
|
||||
return task.WorkflowInterface{}, http.StatusBadRequest, errors.New("the draft must be a definition of the workflow being run")
|
||||
}
|
||||
collection, err := s.workflowCollection(ctx)
|
||||
collection, err := a.workflowCollection(ctx)
|
||||
if err != nil {
|
||||
return task.WorkflowInterface{}, http.StatusServiceUnavailable, errors.New("workflow definitions unavailable")
|
||||
}
|
||||
@@ -166,7 +192,7 @@ func (s *Server) checkDraft(ctx context.Context, id, draft string) (task.Workflo
|
||||
if err != nil {
|
||||
return task.WorkflowInterface{}, http.StatusInternalServerError, err
|
||||
}
|
||||
if _, err := s.ControlPlane.Command(ctx, &controlpb.CommandRequest{Kind: workflowDefinitionsKind, Command: "validate", ValueJson: value}); err != nil {
|
||||
if _, err := a.controlPlane.Command(ctx, &controlpb.CommandRequest{Kind: workflowDefinitionsKind, Command: "validate", ValueJson: value}); err != nil {
|
||||
if status.Code(err) == codes.InvalidArgument {
|
||||
return task.WorkflowInterface{}, http.StatusBadRequest, errors.New(status.Convert(err).Message())
|
||||
}
|
||||
@@ -183,7 +209,7 @@ func (s *Server) checkDraft(ctx context.Context, id, draft string) (task.Workflo
|
||||
// workflow's repository mode and the configured repositories, and returns it
|
||||
// split. A workflow that takes none refuses one; one that requires it refuses
|
||||
// its absence.
|
||||
func (s *Server) workRequestRepository(ctx context.Context, mode task.RepositoryMode, requested string) (owner, repo string, status int, err error) {
|
||||
func (a *workflowsAPI) workRequestRepository(ctx context.Context, mode task.RepositoryMode, requested string) (owner, repo string, status int, err error) {
|
||||
switch {
|
||||
case requested == "" && mode == task.RepositoryRequired:
|
||||
return "", "", http.StatusBadRequest, errors.New("this workflow needs a repository")
|
||||
@@ -196,7 +222,7 @@ func (s *Server) workRequestRepository(ctx context.Context, mode task.Repository
|
||||
if !ok || owner == "" || repo == "" || strings.Contains(repo, "/") {
|
||||
return "", "", http.StatusBadRequest, errors.New("repository must be owner/name")
|
||||
}
|
||||
repos, err := s.configuredRepositories(ctx)
|
||||
repos, err := a.configuredRepositories(ctx)
|
||||
if err != nil {
|
||||
return "", "", http.StatusServiceUnavailable, err
|
||||
}
|
||||
@@ -215,8 +241,8 @@ func (s *Server) workRequestRepository(ctx context.Context, mode task.Repository
|
||||
|
||||
// handleRepositories lists configured names without requiring permission to
|
||||
// read or edit the organisation's full settings document.
|
||||
func (s *Server) handleRepositories(w http.ResponseWriter, r *http.Request) {
|
||||
repos, err := s.configuredRepositories(r.Context())
|
||||
func (a *workflowsAPI) handleRepositories(w http.ResponseWriter, r *http.Request) {
|
||||
repos, err := a.configuredRepositories(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, "Configured repositories are unavailable.", http.StatusServiceUnavailable)
|
||||
return
|
||||
@@ -232,11 +258,11 @@ func (s *Server) handleRepositories(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, names)
|
||||
}
|
||||
|
||||
func (s *Server) configuredRepositories(ctx context.Context) ([]config.Repo, error) {
|
||||
if s.ControlPlane == nil {
|
||||
func (a *workflowsAPI) configuredRepositories(ctx context.Context) ([]config.Repo, error) {
|
||||
if a.controlPlane == nil {
|
||||
return nil, errors.New("configured repositories unavailable")
|
||||
}
|
||||
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: "repository-policies"})
|
||||
response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: "repository-policies"})
|
||||
if err != nil || response.Resource == nil {
|
||||
return nil, errors.New("configured repositories unavailable")
|
||||
}
|
||||
@@ -249,12 +275,12 @@ func (s *Server) configuredRepositories(ctx context.Context) ([]config.Repo, err
|
||||
|
||||
// enabledWorkflowInterface returns a workflow's declared interface and whether
|
||||
// it is defined and enabled for the caller's org.
|
||||
func (s *Server) enabledWorkflowInterface(ctx context.Context, id string) (task.WorkflowInterface, bool, error) {
|
||||
entry, found, err := s.workflowEntry(ctx, id)
|
||||
func (a *workflowsAPI) enabledWorkflowInterface(ctx context.Context, id string) (task.WorkflowInterface, bool, error) {
|
||||
entry, found, err := a.workflowEntry(ctx, id)
|
||||
if err != nil || !found {
|
||||
return task.WorkflowInterface{}, false, err
|
||||
}
|
||||
enablement, _, err := s.workflowEnablement(ctx)
|
||||
enablement, _, err := a.workflowEnablement(ctx)
|
||||
if err != nil || !enablement.Enabled(org.OrgFromContext(ctx), id) {
|
||||
return task.WorkflowInterface{}, false, err
|
||||
}
|
||||
@@ -265,14 +291,14 @@ func (s *Server) enabledWorkflowInterface(ctx context.Context, id string) (task.
|
||||
return iface, true, nil
|
||||
}
|
||||
|
||||
func (s *Server) hasWorkflowDefinition(ctx context.Context, id string) (bool, error) {
|
||||
_, found, err := s.workflowEntry(ctx, id)
|
||||
func (a *workflowsAPI) hasWorkflowDefinition(ctx context.Context, id string) (bool, error) {
|
||||
_, found, err := a.workflowEntry(ctx, id)
|
||||
return found, err
|
||||
}
|
||||
|
||||
// workflowEntry returns the stored definition of workflow id.
|
||||
func (s *Server) workflowEntry(ctx context.Context, id string) (task.WorkflowDefinitionEntry, bool, error) {
|
||||
collection, err := s.workflowCollection(ctx)
|
||||
func (a *workflowsAPI) workflowEntry(ctx context.Context, id string) (task.WorkflowDefinitionEntry, bool, error) {
|
||||
collection, err := a.workflowCollection(ctx)
|
||||
if err != nil {
|
||||
return task.WorkflowDefinitionEntry{}, false, err
|
||||
}
|
||||
@@ -280,11 +306,11 @@ func (s *Server) workflowEntry(ctx context.Context, id string) (task.WorkflowDef
|
||||
return entry, found, nil
|
||||
}
|
||||
|
||||
func (s *Server) workflowCollection(ctx context.Context) (task.WorkflowDefinitionCollection, error) {
|
||||
if s.ControlPlane == nil {
|
||||
func (a *workflowsAPI) workflowCollection(ctx context.Context) (task.WorkflowDefinitionCollection, error) {
|
||||
if a.controlPlane == nil {
|
||||
return task.WorkflowDefinitionCollection{}, nil
|
||||
}
|
||||
response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowDefinitionsKind})
|
||||
response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowDefinitionsKind})
|
||||
if err != nil {
|
||||
return task.WorkflowDefinitionCollection{}, err
|
||||
}
|
||||
@@ -298,15 +324,15 @@ func (s *Server) workflowCollection(ctx context.Context) (task.WorkflowDefinitio
|
||||
return collection, nil
|
||||
}
|
||||
|
||||
func (s *Server) workflowDefinitions(ctx context.Context) ([]task.Definition, error) {
|
||||
if s.ControlPlane == nil {
|
||||
func (a *workflowsAPI) workflowDefinitions(ctx context.Context) ([]task.Definition, error) {
|
||||
if a.controlPlane == nil {
|
||||
return nil, nil
|
||||
}
|
||||
collection, err := s.workflowCollection(ctx)
|
||||
collection, err := a.workflowCollection(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
enablement, _, err := s.workflowEnablement(ctx)
|
||||
enablement, _, err := a.workflowEnablement(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -28,7 +28,7 @@ func TestWorkRequestRejectsLongTitle(t *testing.T) {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("X-Archie-CSRF", "1")
|
||||
response := httptest.NewRecorder()
|
||||
(&Server{}).handleWorkRequest(response, request)
|
||||
newWorkflowsAPI(&Server{}).handleWorkRequest(response, request)
|
||||
if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "title must be 80 characters or fewer") {
|
||||
t.Fatalf("response = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
@@ -81,7 +81,7 @@ func TestWorkRequestRequester(t *testing.T) {
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
tasks := &workRequestTasks{}
|
||||
response := httptest.NewRecorder()
|
||||
(&Server{Store: tasks, ControlPlane: workRequestControl{}}).handleWorkRequest(response, req)
|
||||
newWorkflowsAPI(&Server{Store: tasks, ControlPlane: workRequestControl{}}).handleWorkRequest(response, req)
|
||||
if response.Code != tt.status || tasks.requester != tt.requester {
|
||||
t.Fatalf("response = %d %s, requester = %q; want %d, %q", response.Code, response.Body.String(), tasks.requester, tt.status, tt.requester)
|
||||
}
|
||||
@@ -178,9 +178,7 @@ onUnmounted(() => {
|
||||
{{ elapsedText }} of 24h elapsed (default window)
|
||||
</p>
|
||||
</div>
|
||||
<p v-else class="mt-3 text-caption text-fg-muted">
|
||||
Install time not recorded, so the window cannot be measured.
|
||||
</p>
|
||||
<p v-else class="mt-3 text-caption text-fg-muted">Install time not recorded, so the window cannot be measured.</p>
|
||||
</template>
|
||||
</template>
|
||||
</Section>
|
||||
|
||||
@@ -129,9 +129,7 @@ const unavailable = computed(() => !!connection.value.type && !extensions.forges
|
||||
/>
|
||||
<span class="font-mono text-xs">{{ operation }}</span>
|
||||
</Label>
|
||||
<Button variant="ghost" size="sm" @click="connection = removePermit(connection, identity)">
|
||||
Remove
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" @click="connection = removePermit(connection, identity)">Remove</Button>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" @click="connection = addPermit(connection)">
|
||||
<Plus data-icon="inline-start" />Add identity
|
||||
|
||||
Reference in new issue
Block a user