556 lines
19 KiB
Go
556 lines
19 KiB
Go
package webui
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
|
"github.com/samcharles93/archie-core/internal/domain/storepkg"
|
|
"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("PUT /api/extensions/{name}/settings", a.handleExtensionSettings)
|
|
mux.HandleFunc("DELETE /api/extensions/{name}", a.handleExtensionRemove)
|
|
}
|
|
|
|
type authorityView struct {
|
|
CredentialServices []string `json:"credential_services"`
|
|
EgressHosts []string `json:"egress_hosts"`
|
|
ForgePermissions []string `json:"forge_permissions"`
|
|
Triggers []string `json:"triggers"`
|
|
Tools []string `json:"tools"`
|
|
Env []string `json:"env"`
|
|
}
|
|
|
|
func authorityOf(a storepkg.Authority) authorityView {
|
|
return authorityView{
|
|
CredentialServices: orEmpty(a.CredentialServices), EgressHosts: orEmpty(a.EgressHosts),
|
|
ForgePermissions: orEmpty(a.ForgePermissions), Triggers: orEmpty(a.Triggers),
|
|
Tools: orEmpty(a.Tools), Env: orEmpty(a.Env),
|
|
}
|
|
}
|
|
|
|
func orEmpty[T any](s []T) []T {
|
|
if s == nil {
|
|
return []T{}
|
|
}
|
|
return s
|
|
}
|
|
|
|
// ExtensionView is one installed package as the dashboard shows it: what it
|
|
// declares, what the operator accepted, and whether it is enabled.
|
|
type ExtensionView struct {
|
|
Name string `json:"name"`
|
|
DisplayName string `json:"display_name"`
|
|
Description string `json:"description"`
|
|
Version string `json:"version"`
|
|
Reference string `json:"reference"`
|
|
Digest string `json:"digest"`
|
|
Surfaces []string `json:"surfaces"`
|
|
Declared authorityView `json:"declared"`
|
|
Accepted *authorityView `json:"accepted"`
|
|
Enabled bool `json:"enabled"`
|
|
// Pending is an update waiting for approval, with only the grants it adds
|
|
// to what the operator accepted.
|
|
Pending *pendingView `json:"pending"`
|
|
CanRollback bool `json:"can_rollback"`
|
|
// UpdatePolicy is "manual" or "auto".
|
|
UpdatePolicy string `json:"update_policy"`
|
|
// SettingsSchema is what the package declares an operator enters, and
|
|
// Settings the values entered; a secret's value is its reference.
|
|
SettingsSchema []storepkg.Setting `json:"settings_schema"`
|
|
Settings map[string]string `json:"settings"`
|
|
}
|
|
|
|
type pendingView struct {
|
|
Digest string `json:"digest"`
|
|
Added authorityView `json:"added"`
|
|
}
|
|
|
|
// addedGrants returns the grants want asks for that held does not grant.
|
|
func addedGrants(held *storepkg.Authority, want storepkg.Authority) authorityView {
|
|
var have storepkg.Authority
|
|
if held != nil {
|
|
have = *held
|
|
}
|
|
missing := func(have, want []string) []string {
|
|
return slices.DeleteFunc(slices.Clone(want), func(grant string) bool { return slices.Contains(have, grant) })
|
|
}
|
|
return authorityOf(storepkg.Authority{
|
|
CredentialServices: missing(have.CredentialServices, want.CredentialServices),
|
|
EgressHosts: missing(have.EgressHosts, want.EgressHosts),
|
|
ForgePermissions: missing(have.ForgePermissions, want.ForgePermissions),
|
|
Triggers: missing(have.Triggers, want.Triggers),
|
|
Tools: missing(have.Tools, want.Tools),
|
|
Env: missing(have.Env, want.Env),
|
|
})
|
|
}
|
|
|
|
func extensionView(p storepkg.Installed, enabled bool) ExtensionView {
|
|
view := ExtensionView{
|
|
Name: p.Name, DisplayName: p.Descriptor.DisplayName, Description: p.Descriptor.Description,
|
|
Version: p.Descriptor.Version, Reference: p.Reference, Digest: p.Digest,
|
|
Surfaces: []string{}, Declared: authorityOf(p.Descriptor.Authority), Enabled: enabled,
|
|
SettingsSchema: orEmpty(p.Descriptor.Settings), Settings: map[string]string{},
|
|
}
|
|
for _, extension := range p.Descriptor.Contributes.Extensions {
|
|
if !slices.Contains(view.Surfaces, extension.Surface) {
|
|
view.Surfaces = append(view.Surfaces, extension.Surface)
|
|
}
|
|
}
|
|
view.CanRollback = p.Previous != nil
|
|
view.UpdatePolicy = p.UpdatePolicy
|
|
if p.Pending != nil && p.PendingAuthority != nil {
|
|
view.Pending = &pendingView{Digest: p.Pending.Digest, Added: addedGrants(p.AcceptedAuthority, *p.PendingAuthority)}
|
|
}
|
|
if p.AcceptedAuthority != nil {
|
|
accepted := authorityOf(*p.AcceptedAuthority)
|
|
view.Accepted = &accepted
|
|
}
|
|
return view
|
|
}
|
|
|
|
// extensionSettings reads the extension-settings resource and the version a
|
|
// replacement must name.
|
|
func (a *extensionsAPI) extensionSettings(ctx context.Context) (controlplanerpc.ExtensionSettings, int64, error) {
|
|
var doc controlplanerpc.ExtensionSettings
|
|
response, err := a.controlPlane.Query(ctx, &controlpb.QueryRequest{Kind: controlplanerpc.ExtensionSettingsKind})
|
|
if err != nil {
|
|
return doc, 0, err
|
|
}
|
|
if response.Resource == nil {
|
|
return doc, 0, errors.New("extension settings missing")
|
|
}
|
|
if err := json.Unmarshal(response.Resource.ValueJson, &doc); err != nil {
|
|
return doc, 0, err
|
|
}
|
|
return doc, response.Resource.Version, nil
|
|
}
|
|
|
|
// putExtensionSettings replaces the extension-settings resource at version.
|
|
func (a *extensionsAPI) putExtensionSettings(ctx context.Context, doc controlplanerpc.ExtensionSettings, version int64) error {
|
|
value, err := json.Marshal(doc)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
audit, err := webAudit(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, 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,
|
|
})
|
|
return err
|
|
}
|
|
|
|
// withExtension returns doc with the named extension enabled or disabled,
|
|
// keeping the settings entered for it.
|
|
func withExtension(doc controlplanerpc.ExtensionSettings, name string, enabled bool) controlplanerpc.ExtensionSettings {
|
|
next := controlplanerpc.ExtensionSettings{Extensions: slices.Clone(doc.Extensions)}
|
|
for i := range next.Extensions {
|
|
if next.Extensions[i].Name == name {
|
|
next.Extensions[i].Enabled = enabled
|
|
return next
|
|
}
|
|
}
|
|
next.Extensions = append(next.Extensions, controlplanerpc.ExtensionSetting{Name: name, Enabled: enabled})
|
|
return next
|
|
}
|
|
|
|
func (a *extensionsAPI) extensionsReady(w http.ResponseWriter) bool {
|
|
if a.packages == nil || a.controlPlane == nil {
|
|
http.Error(w, "extensions unavailable", http.StatusServiceUnavailable)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func writePackageError(w http.ResponseWriter, err error) {
|
|
switch {
|
|
case errors.Is(err, storepkg.ErrNotFound):
|
|
http.Error(w, "extension not installed", http.StatusNotFound)
|
|
case errors.Is(err, storepkg.ErrNoPendingUpdate), errors.Is(err, storepkg.ErrNoPrevious), errors.Is(err, storepkg.ErrRequired):
|
|
http.Error(w, err.Error(), http.StatusConflict)
|
|
case errors.Is(err, storepkg.ErrInvalidPolicy):
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
case errors.Is(err, storepkg.ErrInstalled):
|
|
http.Error(w, "extension already installed", http.StatusConflict)
|
|
default:
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
}
|
|
}
|
|
|
|
// handleExtensions lists the installed packages with their authority and
|
|
// enabled state.
|
|
func (a *extensionsAPI) handleExtensions(w http.ResponseWriter, r *http.Request) {
|
|
if !a.extensionsReady(w) {
|
|
return
|
|
}
|
|
installed, err := a.packages.ListInstalled(r.Context())
|
|
if err != nil {
|
|
writePackageError(w, err)
|
|
return
|
|
}
|
|
doc, _, err := a.extensionSettings(r.Context())
|
|
if err != nil {
|
|
writeControlPlaneError(w, err)
|
|
return
|
|
}
|
|
stored := make(map[string]controlplanerpc.ExtensionSetting, len(doc.Extensions))
|
|
for _, setting := range doc.Extensions {
|
|
stored[setting.Name] = setting
|
|
}
|
|
views := make([]ExtensionView, 0, len(installed))
|
|
for _, p := range installed {
|
|
view := extensionView(p, stored[p.Name].Enabled)
|
|
if values := stored[p.Name].Settings; values != nil {
|
|
view.Settings = values
|
|
}
|
|
views = append(views, view)
|
|
}
|
|
writeJSON(w, map[string]any{"extensions": views})
|
|
}
|
|
|
|
type installExtensionRequest struct {
|
|
Name string `json:"name"`
|
|
Reference string `json:"reference"`
|
|
Digest string `json:"digest"`
|
|
}
|
|
|
|
// handleExtensionInstall installs a digest-pinned package. It does not enable
|
|
// it and does not accept its authority: both are separate operator actions.
|
|
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 := a.packages.InstallPackage(r.Context(),
|
|
strings.TrimSpace(request.Name), strings.TrimSpace(request.Reference), strings.TrimSpace(request.Digest))
|
|
if err != nil {
|
|
writePackageError(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, extensionView(p, false))
|
|
}
|
|
|
|
// handleExtensionAccept records the operator's acceptance of exactly the
|
|
// authority the package declares.
|
|
func (a *extensionsAPI) handleExtensionAccept(w http.ResponseWriter, r *http.Request) {
|
|
if !a.extensionsReady(w) {
|
|
return
|
|
}
|
|
name := r.PathValue("name")
|
|
installed, err := a.packages.GetInstalled(r.Context(), name)
|
|
if err != nil {
|
|
writePackageError(w, err)
|
|
return
|
|
}
|
|
p, err := a.packages.AcceptPackageAuthority(r.Context(), name, installed.Descriptor.Authority)
|
|
if err != nil {
|
|
writePackageError(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, extensionView(p, false))
|
|
}
|
|
|
|
// handleExtensionUpdate moves a package to the catalogue's digest: an update
|
|
// that adds no authority applies, one that does waits as pending.
|
|
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 (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 (a *extensionsAPI) handleExtensionRollback(w http.ResponseWriter, r *http.Request) {
|
|
a.packageTransition(w, r, a.packages.RollbackPackage)
|
|
}
|
|
|
|
type updatePolicyRequest struct {
|
|
Policy string `json:"policy"`
|
|
}
|
|
|
|
// handleExtensionUpdatePolicy sets whether the State Store updates a package
|
|
// on its own.
|
|
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 := a.packages.SetPackageUpdatePolicy(r.Context(), r.PathValue("name"), request.Policy)
|
|
if err != nil {
|
|
writePackageError(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, extensionView(p, false))
|
|
}
|
|
|
|
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"))
|
|
if err != nil {
|
|
writePackageError(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, extensionView(p, false))
|
|
}
|
|
|
|
type extensionEnabledRequest struct {
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
|
|
// handleExtensionEnabled enables or disables an installed extension.
|
|
func (a *extensionsAPI) handleExtensionEnabled(w http.ResponseWriter, r *http.Request) {
|
|
if !a.extensionsReady(w) {
|
|
return
|
|
}
|
|
request, ok := decodeBody[extensionEnabledRequest](w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
name := r.PathValue("name")
|
|
if _, err := a.packages.GetInstalled(r.Context(), name); err != nil {
|
|
writePackageError(w, err)
|
|
return
|
|
}
|
|
doc, version, err := a.extensionSettings(r.Context())
|
|
if err != nil {
|
|
writeControlPlaneError(w, err)
|
|
return
|
|
}
|
|
if err := a.putExtensionSettings(r.Context(), withExtension(doc, name, request.Enabled), version); err != nil {
|
|
writeControlPlaneError(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, map[string]any{"name": name, "enabled": request.Enabled})
|
|
}
|
|
|
|
type extensionSettingsRequest struct {
|
|
Settings map[string]string `json:"settings"`
|
|
}
|
|
|
|
// handleExtensionSettings replaces the settings an installed extension runs
|
|
// with. Only the keys its package declares are accepted, and a secret is
|
|
// accepted only as an engine:key reference.
|
|
func (a *extensionsAPI) handleExtensionSettings(w http.ResponseWriter, r *http.Request) {
|
|
if !a.extensionsReady(w) {
|
|
return
|
|
}
|
|
request, ok := decodeBody[extensionSettingsRequest](w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
name := r.PathValue("name")
|
|
installed, err := a.packages.GetInstalled(r.Context(), name)
|
|
if err != nil {
|
|
writePackageError(w, err)
|
|
return
|
|
}
|
|
values, err := declaredSettings(installed.Descriptor.Settings, request.Settings)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
doc, version, err := a.extensionSettings(r.Context())
|
|
if err != nil {
|
|
writeControlPlaneError(w, err)
|
|
return
|
|
}
|
|
if err := a.putExtensionSettings(r.Context(), withSettings(doc, name, values), version); err != nil {
|
|
writeControlPlaneError(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, map[string]any{"name": name, "settings": values})
|
|
}
|
|
|
|
// declaredSettings checks values against the package's declared settings and
|
|
// returns them trimmed, with empty values dropped.
|
|
func declaredSettings(schema []storepkg.Setting, values map[string]string) (map[string]string, error) {
|
|
declared := make(map[string]storepkg.Setting, len(schema))
|
|
for _, setting := range schema {
|
|
declared[setting.Key] = setting
|
|
}
|
|
out := make(map[string]string, len(values))
|
|
for key, value := range values {
|
|
setting, ok := declared[key]
|
|
if !ok {
|
|
return nil, fmt.Errorf("setting %q is not declared by the package", key)
|
|
}
|
|
value = strings.TrimSpace(value)
|
|
if value == "" {
|
|
continue
|
|
}
|
|
if setting.Secret {
|
|
engine, ref, found := strings.Cut(value, ":")
|
|
if !found || engine == "" || ref == "" {
|
|
return nil, fmt.Errorf("%s must be a secret reference (engine:key)", setting.Label)
|
|
}
|
|
}
|
|
value, err := typedSettingValue(setting, value)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out[key] = value
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// typedSettingValue checks a non-empty value against the setting's type and
|
|
// returns its normalised form.
|
|
func typedSettingValue(setting storepkg.Setting, value string) (string, error) {
|
|
label := setting.Label
|
|
switch setting.Kind() {
|
|
case storepkg.SettingNumber:
|
|
if _, err := strconv.ParseFloat(value, 64); err != nil {
|
|
return "", fmt.Errorf("%s must be a number", label)
|
|
}
|
|
case storepkg.SettingBoolean:
|
|
if value != "true" && value != "false" {
|
|
return "", fmt.Errorf("%s must be true or false", label)
|
|
}
|
|
case storepkg.SettingDuration:
|
|
if d, err := time.ParseDuration(value); err != nil || d <= 0 {
|
|
return "", fmt.Errorf("%s must be a duration such as 30s", label)
|
|
}
|
|
case storepkg.SettingList:
|
|
items := strings.Split(value, ",")
|
|
for i, item := range items {
|
|
items[i] = strings.TrimSpace(item)
|
|
if items[i] == "" {
|
|
return "", fmt.Errorf("%s must be a comma-separated list without empty items", label)
|
|
}
|
|
}
|
|
return strings.Join(items, ","), nil
|
|
case storepkg.SettingSelect:
|
|
if !slices.Contains(setting.Options, value) {
|
|
return "", fmt.Errorf("%s must be one of %s", label, strings.Join(setting.Options, ", "))
|
|
}
|
|
}
|
|
return value, nil
|
|
}
|
|
|
|
// withSettings returns doc with the named extension's settings replaced,
|
|
// keeping whether it is enabled.
|
|
func withSettings(doc controlplanerpc.ExtensionSettings, name string, values map[string]string) controlplanerpc.ExtensionSettings {
|
|
next := controlplanerpc.ExtensionSettings{Extensions: slices.Clone(doc.Extensions)}
|
|
for i := range next.Extensions {
|
|
if next.Extensions[i].Name == name {
|
|
next.Extensions[i].Settings = values
|
|
return next
|
|
}
|
|
}
|
|
next.Extensions = append(next.Extensions, controlplanerpc.ExtensionSetting{Name: name, Settings: values})
|
|
return next
|
|
}
|
|
|
|
// handleExtensionRemove uninstalls an extension and disables it, so a later
|
|
// reinstall does not start enabled. Its settings are kept for that reinstall.
|
|
func (a *extensionsAPI) handleExtensionRemove(w http.ResponseWriter, r *http.Request) {
|
|
if !a.extensionsReady(w) {
|
|
return
|
|
}
|
|
name := r.PathValue("name")
|
|
if err := a.packages.RemoveInstalled(r.Context(), name); err != nil {
|
|
writePackageError(w, err)
|
|
return
|
|
}
|
|
if doc, version, err := a.extensionSettings(r.Context()); err == nil {
|
|
if err := a.putExtensionSettings(r.Context(), withExtension(doc, name, false), version); err != nil {
|
|
a.log.WarnContext(r.Context(), "disable removed extension", "name", name, "err", err)
|
|
}
|
|
}
|
|
writeJSON(w, map[string]any{"name": name, "removed": true})
|
|
}
|
|
|
|
// catalogueView is one package the catalogue offers, marked when this org has
|
|
// it installed.
|
|
type catalogueView struct {
|
|
storepkg.CatalogueEntry
|
|
Installed bool `json:"installed"`
|
|
}
|
|
|
|
// handleCatalogue lists the packages the verified catalogue offers.
|
|
func (a *extensionsAPI) handleCatalogue(w http.ResponseWriter, r *http.Request) {
|
|
if !a.extensionsReady(w) {
|
|
return
|
|
}
|
|
catalogue, err := a.packages.ListCatalogue(r.Context())
|
|
if err != nil {
|
|
http.Error(w, "catalogue unavailable: "+err.Error(), http.StatusBadGateway)
|
|
return
|
|
}
|
|
installed, err := a.packages.ListInstalled(r.Context())
|
|
if err != nil {
|
|
writePackageError(w, err)
|
|
return
|
|
}
|
|
have := make(map[string]bool, len(installed))
|
|
for _, p := range installed {
|
|
have[p.Name] = true
|
|
}
|
|
out := make([]catalogueView, 0, len(catalogue.Packages))
|
|
for _, entry := range catalogue.Packages {
|
|
out = append(out, catalogueView{CatalogueEntry: entry, Installed: have[entry.Name]})
|
|
}
|
|
writeJSON(w, out)
|
|
}
|
|
|
|
// handleCatalogueInstall installs one catalogue package by name, at the digest
|
|
// the verified catalogue pins.
|
|
func (a *extensionsAPI) handleCatalogueInstall(w http.ResponseWriter, r *http.Request) {
|
|
if !a.extensionsReady(w) {
|
|
return
|
|
}
|
|
p, err := a.packages.InstallFromCatalogue(r.Context(), r.PathValue("name"))
|
|
if err != nil {
|
|
writePackageError(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, extensionView(p, false))
|
|
}
|