* fix(postgres): scope OpenPRs to the caller's org A principal-carrying caller read every org's pr_open tasks. The query now honours the request scope; the daemon's unscoped review scan still sees all orgs. Issue: archie-core-kgxw.23 * fix(statestore): serve task logs only to the task's org ReadTaskLog and StreamTaskLogContent took a task ID and read the file with no org check. The State Store's task-log reader now confirms the task is visible under the caller's scope first; unscoped services read as before. Issue: archie-core-kgxw.24 * fix(postgres): scope ListPolicies to the caller's org Every org's policy text reached any principal-carrying caller. A scoped read now sees its own org's policies, plus instance policies when scoped to the system org. The engines and the lockout guard decide for every org, so they read the full chain unscoped: the dashboard engine loads without the request's principal and the guard lifts the caller's scope. Issue: archie-core-kgxw.25 * fix(postgres): scope identity reads to the caller's org ListIdentities and GetIdentity (and its alias fallback) returned every identity to any caller. A caller scoped to an org now sees only that org's members and assigned agents; the system org and unscoped services still see the whole instance. Issue: archie-core-kgxw.26 * fix(postgres): hide instance status from other orgs ListPresence, ListChannelStatus, ListApplyStatus and GetConfigSnapshot answered any org principal with instance-wide state. They now return nothing unless the request is unscoped or scoped to the system org. The dashboard reads the published config as itself, since its handlers project it for callers of every org. Issue: archie-core-kgxw.27 * feat(postgres): assign new agents an org and role at creation A bot or service account created through the API served no org until the next State Store boot granted it one. Create now assigns it to the org the request acts in with the developer role in the same transaction, so it is authorized immediately. Issue: archie-core-kgxw.14 * feat(edastore): create event records in a chosen workspace Sources are created in a workspace of the caller's org, the default one when none is named; event types and bindings take their source's workspace and mappings their event type's, the same rule the org backfill applied. The binding, mapping and event type contracts carry the workspace, the four list endpoints accept ?workspace=, and the Events page has a workspace selector that filters every step and picks where a new source goes. Issue: archie-core-kgxw.11 * feat(webui): authorize a record in its workspace The API built every access request with no workspace, so workspace policies and per-workspace roles never applied. A request naming a source, binding, mapping, event type or task now reads the record's workspace under the caller's scope and authorizes in it; tasks carry their workspace on the State Store contract for this. Issue: archie-core-kgxw.9 * feat(access): expose workspace environment to policies Policies can test resource.workspace.environment. The workspace attribute is the workspace entity, which carries its environment; the principal brings its org's workspaces from the State Store, so the dashboard and the daemon's run checks describe a resource's workspace without another lookup, and the daemon now authorizes runs in the task's or binding's workspace. Issue: archie-core-kgxw.10 * fix(webui): ask read_secret when a source secret is read Rotating a source's secret returns its value, but the route asked update, which every developer holds, so no policy could narrow who reads a secret. It now asks read_secret on the secret, which the shipped roles give admins and an object policy can narrow further. Issue: archie-core-kgxw.17 * refactor(org): delete the unused upgrade-incomplete sentinel Nothing returns org.ErrUpgradeIncomplete: the State Store finishes the org upgrade before it serves. Issue: archie-core-kgxw.18
189 lines
6.8 KiB
Go
189 lines
6.8 KiB
Go
package archieui
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"time"
|
|
|
|
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
|
"github.com/samcharles93/archie-core/internal/domain/access"
|
|
"github.com/samcharles93/archie-core/internal/domain/applystatus"
|
|
"github.com/samcharles93/archie-core/internal/domain/presence"
|
|
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/harnessrpc"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
|
"github.com/samcharles93/archie-core/internal/webui"
|
|
)
|
|
|
|
// buildAccessChain starts the live access engine over the stored policies.
|
|
// It refuses every request until Run's first load succeeds and keeps
|
|
// retrying, so a State Store or database that is down or slow at start
|
|
// closes the dashboard rather than opening it or stopping it.
|
|
func buildAccessChain(ctx context.Context, store *staterpc.Client, log *slog.Logger) *infraaccess.Live {
|
|
// The chain decides for every org, so it loads as the dashboard service,
|
|
// never as the person whose policy edit triggered a reload.
|
|
load := func(ctx context.Context) ([]access.Policy, error) {
|
|
return store.ListPolicies(access.WithoutPrincipal(ctx))
|
|
}
|
|
live := infraaccess.NewPending(load, log)
|
|
go live.Run(ctx, applystatus.RestampInterval)
|
|
return live
|
|
}
|
|
|
|
// Run serves the dashboard until ctx is cancelled. It resolves its own
|
|
// options, dials the Gateway and State Store contracts itself, composes the
|
|
// HTTP surface over them, and unwinds listener then clients in reverse order
|
|
// on shutdown.
|
|
func Run(ctx context.Context, options Options) error {
|
|
log := slog.New(slog.NewJSONHandler(os.Stderr, nil)).With("component", "ui")
|
|
log, feed := servicekit.Diagnostics(log, presence.UI)
|
|
opts, err := Resolve(options, log)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
warnPlainHTTP(log, opts)
|
|
var cleanups []func()
|
|
defer func() {
|
|
for _, cleanup := range slices.Backward(cleanups) {
|
|
cleanup()
|
|
}
|
|
}()
|
|
tasks, closeState, err := staterpc.Dial(opts.State.Target, presence.UI, opts.State.Token)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cleanups = append(cleanups, closeState)
|
|
chat, closeGateway, err := gatewayrpc.Dial(opts.Gateway.Target, opts.Gateway.Token)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cleanups = append(cleanups, closeGateway)
|
|
chain := buildAccessChain(ctx, tasks, log)
|
|
provider, err := signInProvider(opts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
authenticate := dashboardAuthenticator(provider, opts, tasks, log)
|
|
login, err := dashboardLoginFlow(provider, opts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
srv := compose(ctx, deps{
|
|
Options: opts,
|
|
Log: log,
|
|
Store: tasks,
|
|
Chat: chat,
|
|
Updates: controlplanerpc.UpdateService(controlplanerpc.NewRPCClient(tasks.ControlPlane()), filepath.Join(configuration.DefaultWorkDir(), "ui-update-deferrals.json")),
|
|
Health: newReadinessRegistry(opts, tasks, chat, chain, provider),
|
|
ControlPlane: tasks.ControlPlane(),
|
|
Identities: tasks,
|
|
Authenticate: authenticate,
|
|
Login: login,
|
|
Access: chain,
|
|
Principals: tasks,
|
|
Denials: tasks,
|
|
})
|
|
stopLogs, err := wireServiceLogs(opts, srv, tasks, chat, feed)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cleanups = append(cleanups, stopLogs)
|
|
if err := wireHarness(opts, srv, &cleanups); err != nil {
|
|
return err
|
|
}
|
|
// Priming event history must not delay the listener.
|
|
go pumpEvents(ctx, srv, opts.EventPollInterval, log)
|
|
go presence.Run(ctx, presence.UI, servicekit.Build(), tasks, srv.Health, log)
|
|
liveCtx, stopLive := context.WithCancel(ctx)
|
|
defer stopLive()
|
|
go srv.RunLive(liveCtx)
|
|
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", opts.Listen)
|
|
if err != nil {
|
|
return fmt.Errorf("listen for ui: %w", err)
|
|
}
|
|
cleanups = append(cleanups, func() { _ = listener.Close() })
|
|
attrs := []any{
|
|
"addr", listener.Addr().String(),
|
|
"open", webui.DashboardURL(listener.Addr().String()),
|
|
"gateway", opts.Gateway.Target,
|
|
"state", opts.State.Target,
|
|
}
|
|
// Name the file holding the token, never the token itself: this line
|
|
// reaches the journal and any log an operator pastes.
|
|
if opts.TokenFile != "" {
|
|
attrs = append(attrs, "token_file", opts.TokenFile)
|
|
}
|
|
log.Info("archie-ui running", attrs...)
|
|
return serve(ctx, listener, srv.Handler(), opts)
|
|
}
|
|
|
|
// warnPlainHTTP names the exposure of a dashboard published off-host. The
|
|
// process serves plain HTTP, so the session cookie and the provider token
|
|
// cross the network in clear unless a TLS-terminating proxy sits in front of
|
|
// it -- which [web].trust_forwarded_headers declares. A loopback bind is
|
|
// reached over a tunnel or on the host, so it needs no warning.
|
|
func warnPlainHTTP(log *slog.Logger, opts Options) {
|
|
if webui.IsLoopback(opts.Listen) || opts.trustForwardedHeaders() {
|
|
return
|
|
}
|
|
log.Warn("dashboard is reachable off-host over plain HTTP; session and provider tokens travel in clear unless TLS terminates in front of it (set [web].trust_forwarded_headers behind a TLS proxy)",
|
|
"listen", opts.Listen)
|
|
}
|
|
|
|
// wireHarness attaches the setup terminal to the daemon's session contract
|
|
// when the operator configured one, and registers its cleanup.
|
|
func wireHarness(opts Options, srv *webui.Server, cleanups *[]func()) error {
|
|
if opts.Harness.Target == "" {
|
|
return nil
|
|
}
|
|
harness, closeHarness, err := harnessrpc.Dial(opts.Harness.Target, opts.Harness.Token)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
srv.HarnessTerminal = harness
|
|
*cleanups = append(*cleanups, closeHarness)
|
|
return nil
|
|
}
|
|
|
|
// serve runs handler until ctx ends, then shuts down within
|
|
// ShutdownTimeout.
|
|
func serve(ctx context.Context, listener net.Listener, handler http.Handler, opts Options) error {
|
|
server := &http.Server{Handler: handler, ReadHeaderTimeout: opts.ReadHeaderTimeout}
|
|
serveErr := make(chan error, 1)
|
|
go func() { serveErr <- server.Serve(listener) }()
|
|
select {
|
|
case <-ctx.Done():
|
|
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), opts.ShutdownTimeout)
|
|
defer cancel()
|
|
if err := server.Shutdown(shutdownCtx); err != nil {
|
|
// Shutdown returned once the drain deadline elapsed with a request
|
|
// still in flight. Force-close what is left so shutdown finishes
|
|
// and the process exits cleanly rather than carrying a deadline
|
|
// error to the operator as a fatal exit.
|
|
_ = server.Close()
|
|
}
|
|
return nil
|
|
case err := <-serveErr:
|
|
if errors.Is(err, http.ErrServerClosed) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
}
|
|
|
|
func pumpEvents(ctx context.Context, srv *webui.Server, interval time.Duration, log *slog.Logger) {
|
|
if err := srv.PumpEvents(ctx, interval); err != nil {
|
|
log.Error("event pump stopped; the activity feed will only show history", "err", err)
|
|
}
|
|
}
|