feat(connectors): an extension declares the settings it reads, and each accepted package is listed (#2026)
This commit is contained in:
19 files changed
+1702
-272
No files matched your search
@@ -128,6 +128,7 @@ type Tool interface {
|
||||
// Connector is a running connector and what it declared.
|
||||
type Connector struct {
|
||||
name string
|
||||
version string
|
||||
client pb.ConnectorServiceClient
|
||||
eventTypes map[string]*jsonschema.Resolved
|
||||
actions map[string]action
|
||||
@@ -138,6 +139,8 @@ type Connector struct {
|
||||
listens bool
|
||||
// facts says it answers TargetFacts.
|
||||
facts bool
|
||||
// settings is the schema it declared for its operator settings.
|
||||
settings []Setting
|
||||
}
|
||||
|
||||
// open configures a connector and reads its declaration.
|
||||
@@ -153,13 +156,17 @@ func open(ctx context.Context, name string, client pb.ConnectorServiceClient, se
|
||||
return nil, fmt.Errorf("connector %q speaks contract %q, the host speaks %q", name, desc.GetContract(), contractVersion)
|
||||
}
|
||||
c := &Connector{
|
||||
name: name, client: client,
|
||||
name: name, version: desc.GetVersion(), client: client,
|
||||
eventTypes: map[string]*jsonschema.Resolved{},
|
||||
actions: map[string]action{},
|
||||
lookups: map[string]lookup{},
|
||||
deliveries: map[string]*jsonschema.Resolved{},
|
||||
listens: desc.GetListens(),
|
||||
facts: desc.GetTargetFacts(),
|
||||
settings: connectorSettings(desc.GetSettings()),
|
||||
}
|
||||
if err := validateSettingsSchema(c.settings); err != nil {
|
||||
return nil, fmt.Errorf("connector %q: %w", name, err)
|
||||
}
|
||||
return c, c.load(desc)
|
||||
}
|
||||
@@ -303,6 +310,12 @@ func (c *Connector) Declarations() []Declaration {
|
||||
// Name is the connector's accepted name.
|
||||
func (c *Connector) Name() string { return c.name }
|
||||
|
||||
// Version is the connector's own release, as it described itself.
|
||||
func (c *Connector) Version() string { return c.version }
|
||||
|
||||
// SettingsSchema is what the connector declared an operator enters.
|
||||
func (c *Connector) SettingsSchema() []Setting { return c.settings }
|
||||
|
||||
// Parse turns a payload the caller has already verified into typed events,
|
||||
// each checked against its declared schema.
|
||||
func (c *Connector) Parse(ctx context.Context, body []byte, headers map[string]string) ([]Event, error) {
|
||||
|
||||
@@ -100,24 +100,77 @@ func (m *Module) listCredentials(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
views := make([]credentialView, 0, len(creds))
|
||||
for _, c := range creds {
|
||||
fields, err := m.openCredential(c)
|
||||
view, err := m.credentialViewOf(c)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(r.Context(), "open credential", "credential", c.Name, "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't open credential "+c.Name)
|
||||
return
|
||||
}
|
||||
view := credentialView{Name: c.Name, Kind: c.Kind, Fields: map[string]string{}}
|
||||
for name, f := range fields {
|
||||
view.Fields[name] = "stored"
|
||||
if f.Engine != "" {
|
||||
view.Fields[name] = f.Engine + ":" + f.Key
|
||||
}
|
||||
}
|
||||
views = append(views, view)
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, views)
|
||||
}
|
||||
|
||||
func (m *Module) getCredential(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.PathValue("name")
|
||||
c, ok, err := m.store.Credential(r.Context(), m.orgID, name)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(r.Context(), "read credential", "credential", name, "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't read the credential")
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
httpjson.Error(w, http.StatusNotFound, "no such credential")
|
||||
return
|
||||
}
|
||||
view, err := m.credentialViewOf(c)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(r.Context(), "open credential", "credential", name, "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't open the credential")
|
||||
return
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, view)
|
||||
}
|
||||
|
||||
// credentialViewOf says where each field comes from: stored, or the secret
|
||||
// engine and key that resolves it. The value is never returned.
|
||||
func (m *Module) credentialViewOf(c store.Credential) (credentialView, error) {
|
||||
fields, err := m.openCredential(c)
|
||||
if err != nil {
|
||||
return credentialView{}, err
|
||||
}
|
||||
view := credentialView{Name: c.Name, Kind: c.Kind, Fields: map[string]string{}}
|
||||
for name, f := range fields {
|
||||
view.Fields[name] = "stored"
|
||||
if f.Engine != "" {
|
||||
view.Fields[name] = f.Engine + ":" + f.Key
|
||||
}
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// BearerToken returns the token a bearer credential holds, resolved through an
|
||||
// engine when it names one. It is how a setting references a credential by
|
||||
// name without the dashboard ever reading the value.
|
||||
func (m *Module) BearerToken(ctx context.Context, name string) (string, error) {
|
||||
c, ok, err := m.store.Credential(ctx, m.orgID, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !ok {
|
||||
return "", fmt.Errorf("credential %q doesn't exist", name)
|
||||
}
|
||||
fields, err := m.openCredential(c)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
f, ok := fields["token"]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("credential %q has no token field", name)
|
||||
}
|
||||
return m.resolveField(ctx, store.Accepted{}, f)
|
||||
}
|
||||
|
||||
func checkCredential(req credentialRequest) error {
|
||||
required, optional, ok := kindFields(req.Kind)
|
||||
if !ok {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package connectors
|
||||
|
||||
import (
|
||||
"context"
|
||||
json "encoding/json/v2"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"filippo.io/age"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/seal"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
|
||||
)
|
||||
|
||||
// TestCredentialRoutesNeverReturnASecret guards the credential boundary: a
|
||||
// list or a read says where each field comes from and never what it holds.
|
||||
func TestCredentialRoutesNeverReturnASecret(t *testing.T) {
|
||||
id, err := age.GenerateX25519Identity()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sealer, err := seal.New(id.String(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const secret = "plainly-fake-value-the-route-must-not-return"
|
||||
plain, err := json.Marshal(map[string]Field{"token": {Value: secret}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sealed, err := sealer.Seal("default/ops/bearer", plain)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
module := &Module{
|
||||
orgID: "default",
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
store: &fakeRegistry{creds: []store.Credential{
|
||||
{OrgID: "default", Name: "ops", Kind: "bearer", Sealed: sealed},
|
||||
}},
|
||||
sealer: sealer,
|
||||
}
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
call func(http.ResponseWriter, *http.Request)
|
||||
}{
|
||||
{name: "list", call: module.listCredentials},
|
||||
{name: "read", call: module.getCredential},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/credentials", nil)
|
||||
req.SetPathValue("name", "ops")
|
||||
tt.call(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
body := rec.Body.String()
|
||||
if strings.Contains(body, secret) {
|
||||
t.Fatalf("the route returned the secret: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, "stored") {
|
||||
t.Fatalf("the route didn't say the field is stored: %s", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -28,10 +28,18 @@ var ErrSecretNotFound = errors.New("secret engine holds no such key")
|
||||
// Engine is a running secret engine: an extension that resolves the keys
|
||||
// credentials name, such as entries in a sops file.
|
||||
type Engine struct {
|
||||
name string
|
||||
client sepb.SecretEngineServiceClient
|
||||
name string
|
||||
version string
|
||||
settings []Setting
|
||||
client sepb.SecretEngineServiceClient
|
||||
}
|
||||
|
||||
// Version is the engine's own release, as it described itself.
|
||||
func (e *Engine) Version() string { return e.version }
|
||||
|
||||
// SettingsSchema is what the engine declared an operator enters.
|
||||
func (e *Engine) SettingsSchema() []Setting { return e.settings }
|
||||
|
||||
// Resolve returns the secret the engine holds under key.
|
||||
func (e *Engine) Resolve(ctx context.Context, key string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, resolveTimeout)
|
||||
@@ -64,7 +72,22 @@ func (h *Host) StartEngine(ctx context.Context, spec Spec) (*Engine, error) {
|
||||
h.procs.Stop(spec.Name)
|
||||
return nil, fmt.Errorf("secret engine %q: configure: %w", spec.Name, err)
|
||||
}
|
||||
return &Engine{name: spec.Name, client: client}, nil
|
||||
e := &Engine{name: spec.Name, client: client}
|
||||
desc, err := client.Describe(ctx, &sepb.DescribeRequest{})
|
||||
if status.Code(err) == codes.Unimplemented {
|
||||
// An engine built before settings were declarable still runs.
|
||||
return e, nil
|
||||
}
|
||||
if err != nil {
|
||||
h.procs.Stop(spec.Name)
|
||||
return nil, fmt.Errorf("secret engine %q: describe: %w", spec.Name, err)
|
||||
}
|
||||
e.version, e.settings = desc.GetVersion(), engineSettings(desc.GetSettings())
|
||||
if err := validateSettingsSchema(e.settings); err != nil {
|
||||
h.procs.Stop(spec.Name)
|
||||
return nil, fmt.Errorf("secret engine %q: %w", spec.Name, err)
|
||||
}
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// enginePlugin is the host side of the go-plugin handshake for secret engines.
|
||||
|
||||
@@ -90,13 +90,18 @@ type Guard struct {
|
||||
version string
|
||||
digest string
|
||||
advisory bool
|
||||
values map[string]string
|
||||
settings []Setting
|
||||
client gpb.GuardServiceClient
|
||||
}
|
||||
|
||||
// NewGuard wraps a client of a guard extension. digest is the package digest
|
||||
// recorded with every verdict.
|
||||
func NewGuard(name, version, digest string, advisory bool, client gpb.GuardServiceClient) *Guard {
|
||||
return &Guard{name: name, version: version, digest: digest, advisory: advisory, client: client}
|
||||
func NewGuard(name, version, digest string, advisory bool, values map[string]string, settings []Setting, client gpb.GuardServiceClient) *Guard {
|
||||
return &Guard{
|
||||
name: name, version: version, digest: digest, advisory: advisory,
|
||||
values: values, settings: settings, client: client,
|
||||
}
|
||||
}
|
||||
|
||||
// Name is the guard's name in verdicts.
|
||||
@@ -111,6 +116,14 @@ func (g *Guard) Digest() string { return g.digest }
|
||||
// Advisory says the guard's verdicts set no ceiling.
|
||||
func (g *Guard) Advisory() bool { return g.advisory }
|
||||
|
||||
// SettingsSchema is what the guard declared an operator enters, including the
|
||||
// judge it asks.
|
||||
func (g *Guard) SettingsSchema() []Setting { return g.settings }
|
||||
|
||||
// Settings is what the guard was configured with. A secret is the reference
|
||||
// the guard resolves, never its value.
|
||||
func (g *Guard) Settings() map[string]string { return g.values }
|
||||
|
||||
// Judge asks the guard about one action. ctx bounds the wait.
|
||||
func (g *Guard) Judge(ctx context.Context, r GuardRequest) (GuardAnswer, error) {
|
||||
evidence := make([]*gpb.Evidence, 0, len(r.Evidence))
|
||||
@@ -197,7 +210,12 @@ func (h *Host) StartGuard(ctx context.Context, spec Spec) (*Guard, error) {
|
||||
h.procs.Stop(spec.Name)
|
||||
return nil, fmt.Errorf("guard %q: describe: %w", spec.Name, err)
|
||||
}
|
||||
return NewGuard(spec.Name, desc.GetVersion(), spec.SHA256, desc.GetAdvisory(), client), nil
|
||||
settings := guardSettings(desc.GetSettings())
|
||||
if err := validateSettingsSchema(settings); err != nil {
|
||||
h.procs.Stop(spec.Name)
|
||||
return nil, fmt.Errorf("guard %q: %w", spec.Name, err)
|
||||
}
|
||||
return NewGuard(spec.Name, desc.GetVersion(), spec.SHA256, desc.GetAdvisory(), spec.Settings, settings, client), nil
|
||||
}
|
||||
|
||||
// guardPlugin is the host side of the go-plugin handshake for guards.
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package connectors
|
||||
|
||||
import (
|
||||
"encoding/json/jsontext"
|
||||
json "encoding/json/v2"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
|
||||
)
|
||||
|
||||
// ExtensionView is one accepted package as the dashboard shows it: what it is,
|
||||
// whether it is running, and the settings and credential slots it was given.
|
||||
// It never carries a secret: a credential is named, and a secret setting is
|
||||
// the reference the extension resolves.
|
||||
type ExtensionView struct {
|
||||
Name string `json:"name"`
|
||||
Contract string `json:"contract"`
|
||||
State string `json:"state"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Digest string `json:"digest"`
|
||||
Path string `json:"path,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Args []string `json:"args,omitempty"`
|
||||
Egress []string `json:"egress"`
|
||||
Env []string `json:"env"`
|
||||
Settings map[string]string `json:"settings"`
|
||||
SettingsSchema []Setting `json:"settings_schema"`
|
||||
Credentials map[string]string `json:"credentials"`
|
||||
Tools jsontext.Value `json:"tools,omitempty"`
|
||||
}
|
||||
|
||||
// list returns the accepted packages of one contract, in name order.
|
||||
func (m *Module) list(contract string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
accepted, err := m.store.List(r.Context(), m.orgID)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(r.Context(), "list accepted packages", "contract", contract, "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't read the accepted packages")
|
||||
return
|
||||
}
|
||||
views := make([]ExtensionView, 0, len(accepted))
|
||||
for _, a := range accepted {
|
||||
if a.Contract != contract {
|
||||
continue
|
||||
}
|
||||
view, err := m.viewOf(a)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(r.Context(), "read accepted package", "package", a.Name, "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't read "+a.Name)
|
||||
return
|
||||
}
|
||||
views = append(views, view)
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, views)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Module) viewOf(a store.Accepted) (ExtensionView, error) {
|
||||
view := ExtensionView{
|
||||
Name: a.Name, Contract: a.Contract, Digest: a.SHA256, Path: a.Path, URL: a.URL,
|
||||
Args: a.Args, Egress: a.Egress, Env: a.Env, Tools: a.Tools,
|
||||
Settings: map[string]string{}, Credentials: map[string]string{}, SettingsSchema: []Setting{},
|
||||
}
|
||||
if len(a.Settings) > 0 {
|
||||
if err := json.Unmarshal(a.Settings, &view.Settings); err != nil {
|
||||
return ExtensionView{}, fmt.Errorf("settings: %w", err)
|
||||
}
|
||||
}
|
||||
if len(a.Credentials) > 0 {
|
||||
if err := json.Unmarshal(a.Credentials, &view.Credentials); err != nil {
|
||||
return ExtensionView{}, fmt.Errorf("credentials: %w", err)
|
||||
}
|
||||
}
|
||||
state, reason, version, schema := m.stateOf(a)
|
||||
view.State, view.Error, view.Version, view.SettingsSchema = state, reason, version, schema
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// stateOf reports whether a package is running, and what it declared.
|
||||
func (m *Module) stateOf(a store.Accepted) (state, reason, version string, schema []Setting) {
|
||||
m.mu.RLock()
|
||||
reason = m.failed[a.Name]
|
||||
connector, running := m.running[a.Name]
|
||||
engine, isEngine := m.engines[a.Name]
|
||||
guard, isGuard := m.guards[a.Name]
|
||||
server, isServer := m.servers[a.Name]
|
||||
m.mu.RUnlock()
|
||||
|
||||
switch {
|
||||
case reason != "":
|
||||
return "failed", reason, "", nil
|
||||
case running:
|
||||
return "running", "", connector.Version(), connector.SettingsSchema()
|
||||
case isEngine:
|
||||
return "running", "", engine.Version(), engine.SettingsSchema()
|
||||
case isGuard:
|
||||
return "running", "", guard.Version(), guard.SettingsSchema()
|
||||
case isServer:
|
||||
if err := server.Ready(); err != nil {
|
||||
return "failed", err.Error(), "", server.SettingsSchema()
|
||||
}
|
||||
return "running", "", "", server.SettingsSchema()
|
||||
}
|
||||
return "stopped", "", "", nil
|
||||
}
|
||||
|
||||
// schemaOf returns the settings schema of a package that is running now.
|
||||
func (m *Module) schemaOf(name string) ([]Setting, bool) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
switch {
|
||||
case m.running[name] != nil:
|
||||
return m.running[name].SettingsSchema(), true
|
||||
case m.engines[name] != nil:
|
||||
return m.engines[name].SettingsSchema(), true
|
||||
case m.guards[name] != nil:
|
||||
return m.guards[name].SettingsSchema(), true
|
||||
case m.servers[name] != nil:
|
||||
return m.servers[name].SettingsSchema(), true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// checkAccepted checks an acceptance's settings against the schema the package
|
||||
// declared, once it is known.
|
||||
func (m *Module) checkAccepted(a store.Accepted) error {
|
||||
schema, ok := m.schemaOf(a.Name)
|
||||
if !ok || len(schema) == 0 {
|
||||
return nil
|
||||
}
|
||||
var values map[string]string
|
||||
if len(a.Settings) > 0 {
|
||||
if err := json.Unmarshal(a.Settings, &values); err != nil {
|
||||
return fmt.Errorf("settings: %w", err)
|
||||
}
|
||||
}
|
||||
_, err := checkSettings(schema, values)
|
||||
return err
|
||||
}
|
||||
@@ -125,6 +125,17 @@ func (h *Host) NewServer(spec ServerSpec) *Server {
|
||||
return s
|
||||
}
|
||||
|
||||
// SettingsSchema names the environment settings the acceptance gave a stdio
|
||||
// server. MCP has no configuration channel, so the keys are the declaration.
|
||||
func (s *Server) SettingsSchema() []Setting {
|
||||
out := make([]Setting, 0, len(s.spec.Settings))
|
||||
for _, kv := range s.spec.Settings {
|
||||
key, _, _ := strings.Cut(kv, "=")
|
||||
out = append(out, Setting{Key: key, Label: key})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Declarations lists the tools the acceptance permits, in name order.
|
||||
func (s *Server) Declarations() []Declaration {
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -158,6 +158,15 @@ func (m *Module) acceptServer(w http.ResponseWriter, r *http.Request) {
|
||||
httpjson.Error(w, http.StatusUnprocessableEntity, err.Error())
|
||||
return
|
||||
}
|
||||
if err := m.checkAccepted(a); err != nil {
|
||||
_, _ = m.store.Delete(context.WithoutCancel(r.Context()), m.orgID, name)
|
||||
m.release(name)
|
||||
m.mu.Lock()
|
||||
delete(m.failed, name)
|
||||
m.mu.Unlock()
|
||||
httpjson.Error(w, http.StatusUnprocessableEntity, err.Error())
|
||||
return
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, map[string]string{"name": name, "state": "running"})
|
||||
}
|
||||
|
||||
|
||||
@@ -261,6 +261,11 @@ func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handle
|
||||
mux.Handle("DELETE /api/mcp-servers/{name}", guard(m.remove(store.ContractMCP)))
|
||||
mux.Handle("PUT /api/credentials/{name}", guard(http.HandlerFunc(m.putCredential)))
|
||||
mux.Handle("GET /api/credentials", guard(http.HandlerFunc(m.listCredentials)))
|
||||
mux.Handle("GET /api/credentials/{name}", guard(http.HandlerFunc(m.getCredential)))
|
||||
mux.Handle("GET /api/connectors", guard(m.list(store.ContractConnector)))
|
||||
mux.Handle("GET /api/secret-engines", guard(m.list(store.ContractSecretEngine)))
|
||||
mux.Handle("GET /api/guards", guard(m.list(store.ContractGuard)))
|
||||
mux.Handle("GET /api/mcp-servers", guard(m.list(store.ContractMCP)))
|
||||
}
|
||||
|
||||
type acceptRequest struct {
|
||||
@@ -314,6 +319,18 @@ func (m *Module) acceptAs(w http.ResponseWriter, r *http.Request, contract strin
|
||||
httpjson.Error(w, http.StatusUnprocessableEntity, err.Error())
|
||||
return
|
||||
}
|
||||
// The extension declares its settings when it starts. A value it doesn't
|
||||
// declare, or a required one that is missing, is refused now rather than
|
||||
// left for the extension to misread.
|
||||
if err := m.checkAccepted(a); err != nil {
|
||||
_, _ = m.store.Delete(context.WithoutCancel(r.Context()), m.orgID, name)
|
||||
m.release(name)
|
||||
m.mu.Lock()
|
||||
delete(m.failed, name)
|
||||
m.mu.Unlock()
|
||||
httpjson.Error(w, http.StatusUnprocessableEntity, err.Error())
|
||||
return
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, map[string]string{"name": name, "state": "running"})
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,12 @@ func (f *fakeRegistry) Delete(_ context.Context, _, name string) (bool, error) {
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func (f *fakeRegistry) Credential(context.Context, string, string) (store.Credential, bool, error) {
|
||||
func (f *fakeRegistry) Credential(_ context.Context, _, name string) (store.Credential, bool, error) {
|
||||
for _, c := range f.creds {
|
||||
if c.Name == name {
|
||||
return c, true, nil
|
||||
}
|
||||
}
|
||||
return store.Credential{}, false, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
package connectors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
cpb "github.com/samcharles93/archie-core/internal/contracts/connector/v1"
|
||||
gpb "github.com/samcharles93/archie-core/internal/contracts/guard/v1"
|
||||
sepb "github.com/samcharles93/archie-core/internal/contracts/secretengine/v1"
|
||||
)
|
||||
|
||||
// Setting is one value an operator enters for an extension to run. The
|
||||
// extension declares it, and the dashboard renders it.
|
||||
type Setting struct {
|
||||
Key string `json:"key"`
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Secret bool `json:"secret,omitempty"`
|
||||
Required bool `json:"required,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Options []string `json:"options,omitempty"`
|
||||
}
|
||||
|
||||
// Setting types. The empty type is a string.
|
||||
const (
|
||||
SettingString = "string"
|
||||
SettingNumber = "number"
|
||||
SettingBoolean = "boolean"
|
||||
SettingDuration = "duration"
|
||||
SettingList = "list"
|
||||
SettingSelect = "select"
|
||||
SettingText = "text"
|
||||
)
|
||||
|
||||
// kind returns the setting's type with the default applied.
|
||||
func (s Setting) kind() string {
|
||||
if s.Type == "" {
|
||||
return SettingString
|
||||
}
|
||||
return s.Type
|
||||
}
|
||||
|
||||
var settingKey = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
|
||||
|
||||
// validateSettingsSchema checks what an extension declared, so a broken schema
|
||||
// is reported when it starts rather than when a value is edited.
|
||||
func validateSettingsSchema(settings []Setting) error {
|
||||
seen := make(map[string]bool, len(settings))
|
||||
for _, s := range settings {
|
||||
switch {
|
||||
case !settingKey.MatchString(s.Key):
|
||||
return fmt.Errorf("setting %q must be lower-case letters, digits and underscores", s.Key)
|
||||
case seen[s.Key]:
|
||||
return fmt.Errorf("setting %q is declared twice", s.Key)
|
||||
case strings.TrimSpace(s.Label) == "":
|
||||
return fmt.Errorf("setting %q needs a label", s.Key)
|
||||
case s.Secret != strings.HasSuffix(s.Key, "_ref"):
|
||||
return fmt.Errorf("setting %q: a secret setting's key ends in _ref, and only a secret's does", s.Key)
|
||||
}
|
||||
if err := s.validateType(); err != nil {
|
||||
return err
|
||||
}
|
||||
seen[s.Key] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Setting) validateType() error {
|
||||
switch s.kind() {
|
||||
case SettingString, SettingNumber, SettingBoolean, SettingDuration, SettingList, SettingSelect, SettingText:
|
||||
default:
|
||||
return fmt.Errorf("setting %q: unknown type %q", s.Key, s.Type)
|
||||
}
|
||||
if s.Secret && s.kind() != SettingString {
|
||||
return fmt.Errorf("setting %q: a secret setting is a string", s.Key)
|
||||
}
|
||||
if s.Required && s.kind() == SettingBoolean {
|
||||
return fmt.Errorf("setting %q: a boolean cannot be required, false counts as filled", s.Key)
|
||||
}
|
||||
if s.kind() != SettingSelect {
|
||||
if len(s.Options) > 0 {
|
||||
return fmt.Errorf("setting %q: options belong to a select setting", s.Key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(s.Options) == 0 {
|
||||
return fmt.Errorf("setting %q: a select setting needs options", s.Key)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkSettings checks values against the schema the extension declared and
|
||||
// returns them trimmed, with empty values dropped.
|
||||
func checkSettings(schema []Setting, values map[string]string) (map[string]string, error) {
|
||||
declared := make(map[string]Setting, len(schema))
|
||||
for _, s := range schema {
|
||||
declared[s.Key] = s
|
||||
}
|
||||
out := make(map[string]string, len(values))
|
||||
for key, value := range values {
|
||||
s, ok := declared[key]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("setting %q is not declared by the extension", key)
|
||||
}
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
continue
|
||||
}
|
||||
checked, err := typedValue(s, value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[key] = checked
|
||||
}
|
||||
for _, s := range schema {
|
||||
if s.Required && out[s.Key] == "" {
|
||||
return nil, fmt.Errorf("%s is required", s.Label)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// typedValue checks a non-empty value against the setting's type and returns
|
||||
// its normalised form.
|
||||
func typedValue(s Setting, value string) (string, error) {
|
||||
if s.Secret {
|
||||
if err := checkSecretRef(s.Label, value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
switch s.kind() {
|
||||
case SettingNumber:
|
||||
return checkNumber(s.Label, value)
|
||||
case SettingBoolean:
|
||||
return checkBoolean(s.Label, value)
|
||||
case SettingDuration:
|
||||
return checkDuration(s.Label, value)
|
||||
case SettingList:
|
||||
return checkList(s.Label, value)
|
||||
case SettingSelect:
|
||||
return checkSelect(s, value)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func checkSecretRef(label, value string) error {
|
||||
engine, ref, found := strings.Cut(value, ":")
|
||||
if !found || engine == "" || ref == "" {
|
||||
return fmt.Errorf("%s must be a secret reference (engine:key)", label)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkNumber(label, value string) (string, error) {
|
||||
if _, err := strconv.ParseFloat(value, 64); err != nil {
|
||||
return "", fmt.Errorf("%s must be a number", label)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func checkBoolean(label, value string) (string, error) {
|
||||
if value != "true" && value != "false" {
|
||||
return "", fmt.Errorf("%s must be true or false", label)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func checkDuration(label, value string) (string, error) {
|
||||
if d, err := time.ParseDuration(value); err != nil || d <= 0 {
|
||||
return "", fmt.Errorf("%s must be a duration such as 30s", label)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func checkList(label, value string) (string, error) {
|
||||
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
|
||||
}
|
||||
|
||||
func checkSelect(s Setting, value string) (string, error) {
|
||||
if !slices.Contains(s.Options, value) {
|
||||
return "", fmt.Errorf("%s must be one of %s", s.Label, strings.Join(s.Options, ", "))
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// settingTypeName maps a declared type, wire-compatible across the extension
|
||||
// contracts, to its API name.
|
||||
func settingTypeName(t int32) string {
|
||||
switch cpb.SettingType(t) {
|
||||
case cpb.SettingType_SETTING_TYPE_NUMBER:
|
||||
return SettingNumber
|
||||
case cpb.SettingType_SETTING_TYPE_BOOLEAN:
|
||||
return SettingBoolean
|
||||
case cpb.SettingType_SETTING_TYPE_DURATION:
|
||||
return SettingDuration
|
||||
case cpb.SettingType_SETTING_TYPE_LIST:
|
||||
return SettingList
|
||||
case cpb.SettingType_SETTING_TYPE_SELECT:
|
||||
return SettingSelect
|
||||
case cpb.SettingType_SETTING_TYPE_TEXT:
|
||||
return SettingText
|
||||
}
|
||||
return SettingString
|
||||
}
|
||||
|
||||
func connectorSettings(in []*cpb.Setting) []Setting {
|
||||
out := make([]Setting, 0, len(in))
|
||||
for _, s := range in {
|
||||
out = append(out, Setting{
|
||||
Key: s.GetKey(), Label: s.GetLabel(), Description: s.GetDescription(),
|
||||
Secret: s.GetSecret(), Required: s.GetRequired(), Type: settingTypeName(int32(s.GetType())),
|
||||
Options: s.GetOptions(),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func guardSettings(in []*gpb.Setting) []Setting {
|
||||
out := make([]Setting, 0, len(in))
|
||||
for _, s := range in {
|
||||
out = append(out, Setting{
|
||||
Key: s.GetKey(), Label: s.GetLabel(), Description: s.GetDescription(),
|
||||
Secret: s.GetSecret(), Required: s.GetRequired(), Type: settingTypeName(int32(s.GetType())),
|
||||
Options: s.GetOptions(),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func engineSettings(in []*sepb.Setting) []Setting {
|
||||
out := make([]Setting, 0, len(in))
|
||||
for _, s := range in {
|
||||
out = append(out, Setting{
|
||||
Key: s.GetKey(), Label: s.GetLabel(), Description: s.GetDescription(),
|
||||
Secret: s.GetSecret(), Required: s.GetRequired(), Type: settingTypeName(int32(s.GetType())),
|
||||
Options: s.GetOptions(),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -50,7 +50,7 @@ func TestGuardExtensionsDecideAtTheLowestCeiling(t *testing.T) {
|
||||
return &gpb.JudgeResponse{Ceiling: c, Findings: []*gpb.Finding{{Text: "seen", Evidence: "log", Strength: gpb.Strength_STRENGTH_STRONG}}}
|
||||
}
|
||||
guard := func(name string, advisory bool, c *fakeGuardClient) *connectors.Guard {
|
||||
return connectors.NewGuard(name, "1.0.0", "digest-"+name, advisory, c)
|
||||
return connectors.NewGuard(name, "1.0.0", "digest-"+name, advisory, nil, nil, c)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
Reference in new issue
Block a user