Credentials are typed (machine, age), write-only through the API and sealed to the age identity in the bootstrap config. A field holds a value or names a secret engine key; connectors and engines are accepted with credential slots that resolve into their Configure secrets. The secret engine contract gains secrets so an engine can receive its own key.
This commit is contained in:
15 files changed
+759
-48
No files matched your search
@@ -0,0 +1,257 @@
|
||||
package connectors
|
||||
|
||||
import (
|
||||
"context"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
|
||||
)
|
||||
|
||||
// Field is one field of a credential: a value Archie keeps sealed, or the key
|
||||
// a secret engine resolves it from when the extension using it starts.
|
||||
type Field struct {
|
||||
Value string `json:"value,omitzero"`
|
||||
Engine string `json:"engine,omitzero"`
|
||||
Key string `json:"key,omitzero"`
|
||||
}
|
||||
|
||||
// kindFields lists a credential kind's required and optional fields.
|
||||
func kindFields(kind string) (required, optional []string, ok bool) {
|
||||
switch kind {
|
||||
case "machine":
|
||||
return []string{"username", "private_key"}, []string{"private_key_passphrase"}, true
|
||||
case "age":
|
||||
return []string{"identity"}, nil, true
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
type credentialRequest struct {
|
||||
Kind string `json:"kind"`
|
||||
Fields map[string]Field `json:"fields"`
|
||||
}
|
||||
|
||||
// credentialView shows where each field comes from, never a value.
|
||||
type credentialView struct {
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Fields map[string]string `json:"fields"`
|
||||
}
|
||||
|
||||
// putCredential stores a credential sealed, then restarts the extensions that
|
||||
// use it so they are configured with the new values.
|
||||
func (m *Module) putCredential(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.PathValue("name")
|
||||
var req credentialRequest
|
||||
if err := httpjson.Read(r, &req); err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if !validName.MatchString(name) {
|
||||
httpjson.Error(w, http.StatusBadRequest, "a credential needs a lowercase name")
|
||||
return
|
||||
}
|
||||
if err := checkCredential(req); err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
plain, err := json.Marshal(req.Fields)
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
sealed, err := m.sealer.Seal(m.credentialLabel(name, req.Kind), plain)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(r.Context(), "seal credential", "credential", name, "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't seal the credential")
|
||||
return
|
||||
}
|
||||
if err := m.store.PutCredential(r.Context(), store.Credential{OrgID: m.orgID, Name: name, Kind: req.Kind, Sealed: sealed}); err != nil {
|
||||
m.log.ErrorContext(r.Context(), "put credential", "credential", name, "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't save the credential")
|
||||
return
|
||||
}
|
||||
restarted, err := m.relaunchUsers(context.WithoutCancel(r.Context()), name)
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusUnprocessableEntity, err.Error())
|
||||
return
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, map[string]any{"name": name, "kind": req.Kind, "restarted": restarted})
|
||||
}
|
||||
|
||||
func (m *Module) listCredentials(w http.ResponseWriter, r *http.Request) {
|
||||
creds, err := m.store.Credentials(r.Context(), m.orgID)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(r.Context(), "list credentials", "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't list credentials")
|
||||
return
|
||||
}
|
||||
views := make([]credentialView, 0, len(creds))
|
||||
for _, c := range creds {
|
||||
fields, err := m.openCredential(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 checkCredential(req credentialRequest) error {
|
||||
required, optional, ok := kindFields(req.Kind)
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown credential kind %q", req.Kind)
|
||||
}
|
||||
for _, name := range required {
|
||||
if _, ok := req.Fields[name]; !ok {
|
||||
return fmt.Errorf("a %s credential needs %s", req.Kind, name)
|
||||
}
|
||||
}
|
||||
for _, name := range slices.Sorted(maps.Keys(req.Fields)) {
|
||||
if !slices.Contains(required, name) && !slices.Contains(optional, name) {
|
||||
return fmt.Errorf("a %s credential has no field %s", req.Kind, name)
|
||||
}
|
||||
f := req.Fields[name]
|
||||
if (f.Value == "") == (f.Engine == "" || f.Key == "") {
|
||||
return fmt.Errorf("field %s needs either a value or an engine and a key", name)
|
||||
}
|
||||
}
|
||||
return checkPrivateKey(req.Fields["private_key"], req.Fields["private_key_passphrase"])
|
||||
}
|
||||
|
||||
// checkPrivateKey catches a key that won't parse when it is stored, rather
|
||||
// than when a connector first needs it. A key resolved by an engine is checked
|
||||
// when it is resolved.
|
||||
func checkPrivateKey(key, passphrase Field) error {
|
||||
if key.Value == "" {
|
||||
return nil
|
||||
}
|
||||
var err error
|
||||
switch {
|
||||
case passphrase.Value != "":
|
||||
_, err = ssh.ParseRawPrivateKeyWithPassphrase([]byte(key.Value), []byte(passphrase.Value))
|
||||
case passphrase.Engine != "":
|
||||
return nil
|
||||
default:
|
||||
_, err = ssh.ParseRawPrivateKey([]byte(key.Value))
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("private_key: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Module) credentialLabel(name, kind string) string {
|
||||
return m.orgID + "/" + name + "/" + kind
|
||||
}
|
||||
|
||||
func (m *Module) openCredential(c store.Credential) (map[string]Field, error) {
|
||||
plain, err := m.sealer.Open(m.credentialLabel(c.Name, c.Kind), c.Sealed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var fields map[string]Field
|
||||
if err := json.Unmarshal(plain, &fields); err != nil {
|
||||
return nil, fmt.Errorf("credential %q: %w", c.Name, err)
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// secrets resolves an extension's credential slots into the secrets it is
|
||||
// configured with, keyed "slot.field". A secret engine's own credentials must
|
||||
// hold their values: an engine never waits on another engine.
|
||||
func (m *Module) secrets(ctx context.Context, a store.Accepted) (map[string]string, error) {
|
||||
slots, err := decodeSlots(a.Credentials)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[string]string{}
|
||||
for slot, credName := range slots {
|
||||
c, ok, err := m.store.Credential(ctx, m.orgID, credName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("credential %q for slot %q doesn't exist", credName, slot)
|
||||
}
|
||||
fields, err := m.openCredential(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for field, f := range fields {
|
||||
v, err := m.resolveField(ctx, a, f)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("credential %q field %s: %w", credName, field, err)
|
||||
}
|
||||
out[slot+"."+field] = v
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Module) resolveField(ctx context.Context, a store.Accepted, f Field) (string, error) {
|
||||
if f.Engine == "" {
|
||||
return f.Value, nil
|
||||
}
|
||||
if a.Contract == store.ContractSecretEngine {
|
||||
return "", errors.New("a secret engine's own credentials must hold their values")
|
||||
}
|
||||
m.mu.RLock()
|
||||
engine, ok := m.engines[f.Engine]
|
||||
m.mu.RUnlock()
|
||||
if !ok {
|
||||
return "", fmt.Errorf("secret engine %q isn't running", f.Engine)
|
||||
}
|
||||
return engine.Resolve(ctx, f.Key)
|
||||
}
|
||||
|
||||
func decodeSlots(raw []byte) (map[string]string, error) {
|
||||
slots := map[string]string{}
|
||||
if len(raw) == 0 {
|
||||
return slots, nil
|
||||
}
|
||||
if err := json.Unmarshal(raw, &slots); err != nil {
|
||||
return nil, fmt.Errorf("credential slots: %w", err)
|
||||
}
|
||||
return slots, nil
|
||||
}
|
||||
|
||||
// relaunchUsers restarts every accepted extension with a slot naming the
|
||||
// credential, and returns their names.
|
||||
func (m *Module) relaunchUsers(ctx context.Context, credential string) ([]string, error) {
|
||||
accepted, err := m.store.List(ctx, m.orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var restarted []string
|
||||
var errs []error
|
||||
for _, a := range ordered(accepted) {
|
||||
slots, err := decodeSlots(a.Credentials)
|
||||
if err != nil || !slices.Contains(slices.Collect(maps.Values(slots)), credential) {
|
||||
continue
|
||||
}
|
||||
if err := m.launch(ctx, a); err != nil {
|
||||
errs = append(errs, err)
|
||||
continue
|
||||
}
|
||||
restarted = append(restarted, a.Name)
|
||||
}
|
||||
return restarted, errors.Join(errs...)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package connectors
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
goplugin "github.com/hashicorp/go-plugin"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
sepb "github.com/samcharles93/archie-core/internal/contracts/secretengine/v1"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/host"
|
||||
)
|
||||
|
||||
// engineSurface names the secret engine contract in the plugin handshake.
|
||||
const engineSurface = "secretengine"
|
||||
|
||||
// resolveTimeout bounds one secret lookup, so a hung engine can't hold a
|
||||
// connector's start for ever.
|
||||
const resolveTimeout = 30 * time.Second
|
||||
|
||||
// ErrSecretNotFound means a secret engine holds nothing under the key.
|
||||
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
|
||||
}
|
||||
|
||||
// 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)
|
||||
defer cancel()
|
||||
resp, err := e.client.Resolve(ctx, &sepb.ResolveRequest{Key: key})
|
||||
if status.Code(err) == codes.NotFound {
|
||||
return "", fmt.Errorf("secret engine %q: key %q: %w", e.name, key, ErrSecretNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("secret engine %q: %w", e.name, err)
|
||||
}
|
||||
return resp.GetValue(), nil
|
||||
}
|
||||
|
||||
// StartEngine launches a secret engine and configures it with its settings
|
||||
// and its own secrets.
|
||||
func (h *Host) StartEngine(ctx context.Context, spec Spec) (*Engine, error) {
|
||||
raw, err := h.procs.Start(ctx, host.Spec{
|
||||
Name: spec.Name, Path: spec.Path, SHA256: spec.SHA256, Env: spec.Env, Egress: spec.Egress,
|
||||
}, engineSurface, &enginePlugin{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client, ok := raw.(sepb.SecretEngineServiceClient)
|
||||
if !ok {
|
||||
h.procs.Stop(spec.Name)
|
||||
return nil, fmt.Errorf("secret engine %q: plugin is not a secret engine", spec.Name)
|
||||
}
|
||||
if _, err := client.Configure(ctx, &sepb.ConfigureRequest{Settings: spec.Settings, Secrets: spec.Secrets}); err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
// enginePlugin is the host side of the go-plugin handshake for secret engines.
|
||||
type enginePlugin struct {
|
||||
goplugin.NetRPCUnsupportedPlugin
|
||||
}
|
||||
|
||||
func (*enginePlugin) GRPCServer(*goplugin.GRPCBroker, *grpc.Server) error {
|
||||
return errors.New("secret engines are served by extensions, not by the host")
|
||||
}
|
||||
|
||||
func (*enginePlugin) GRPCClient(_ context.Context, _ *goplugin.GRPCBroker, conn *grpc.ClientConn) (any, error) {
|
||||
return sepb.NewSecretEngineServiceClient(conn), nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// Package seal encrypts credentials at rest with age. Each sealed value is
|
||||
// bound to a label naming where it is stored, so a value copied into another
|
||||
// row doesn't open there.
|
||||
package seal
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"filippo.io/age"
|
||||
)
|
||||
|
||||
// ErrWrongLabel means a sealed value was opened under a label other than the
|
||||
// one it was sealed for.
|
||||
var ErrWrongLabel = errors.New("sealed value belongs to a different record")
|
||||
|
||||
// Sealer seals to its own identity and to any backup recipients, and opens
|
||||
// with its identity.
|
||||
type Sealer struct {
|
||||
identity *age.X25519Identity
|
||||
recipients []age.Recipient
|
||||
}
|
||||
|
||||
// New returns a sealer for an age identity ("AGE-SECRET-KEY-1...") and the
|
||||
// backup recipients ("age1...") that can also open what it seals.
|
||||
func New(identity string, backups []string) (*Sealer, error) {
|
||||
id, err := age.ParseX25519Identity(identity)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("age identity: %w", err)
|
||||
}
|
||||
s := &Sealer{identity: id, recipients: []age.Recipient{id.Recipient()}}
|
||||
for _, b := range backups {
|
||||
r, err := age.ParseX25519Recipient(b)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("backup recipient %q: %w", b, err)
|
||||
}
|
||||
s.recipients = append(s.recipients, r)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
type envelope struct {
|
||||
Label string `json:"label"`
|
||||
Data []byte `json:"data"`
|
||||
}
|
||||
|
||||
// Seal encrypts data for label.
|
||||
func (s *Sealer) Seal(label string, data []byte) ([]byte, error) {
|
||||
plain, err := json.Marshal(envelope{Label: label, Data: data})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out bytes.Buffer
|
||||
w, err := age.Encrypt(&out, s.recipients...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("seal: %w", err)
|
||||
}
|
||||
if _, err := w.Write(plain); err != nil {
|
||||
return nil, fmt.Errorf("seal: %w", err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return nil, fmt.Errorf("seal: %w", err)
|
||||
}
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
|
||||
// Open decrypts a value sealed for label.
|
||||
func (s *Sealer) Open(label string, sealed []byte) ([]byte, error) {
|
||||
r, err := age.Decrypt(bytes.NewReader(sealed), s.identity)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open: %w", err)
|
||||
}
|
||||
plain, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open: %w", err)
|
||||
}
|
||||
var env envelope
|
||||
if err := json.Unmarshal(plain, &env); err != nil {
|
||||
return nil, fmt.Errorf("open: %w", err)
|
||||
}
|
||||
if env.Label != label {
|
||||
return nil, ErrWrongLabel
|
||||
}
|
||||
return env.Data, nil
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package seal
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"filippo.io/age"
|
||||
)
|
||||
|
||||
// TestSealedValueOpensOnlyWhereItBelongs guards the credential store's
|
||||
// boundary: a sealed value opens with Archie's identity or a backup key, under
|
||||
// the label it was sealed for, and nowhere else. A value copied into another
|
||||
// row, or read with a stranger's key, stays shut.
|
||||
func TestSealedValueOpensOnlyWhereItBelongs(t *testing.T) {
|
||||
own, backup, stranger := identity(t), identity(t), identity(t)
|
||||
sealer, err := New(own.String(), []string{backup.Recipient().String()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secret := []byte("plainly fake private key")
|
||||
sealed, err := sealer.Seal("default/carina", secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bytes.Contains(sealed, secret) {
|
||||
t.Fatal("sealed value contains the plaintext")
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
with *age.X25519Identity
|
||||
label string
|
||||
wantErr error
|
||||
}{
|
||||
{name: "own identity, own label", with: own, label: "default/carina"},
|
||||
{name: "backup identity", with: backup, label: "default/carina"},
|
||||
{name: "copied to another record", with: own, label: "default/nebula", wantErr: ErrWrongLabel},
|
||||
{name: "a stranger's identity", with: stranger, label: "default/carina", wantErr: age.ErrIncorrectIdentity},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
opener, err := New(tt.with.String(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := opener.Open(tt.label, sealed)
|
||||
if tt.wantErr != nil {
|
||||
var noMatch *age.NoIdentityMatchError
|
||||
if !errors.Is(err, tt.wantErr) && !errors.As(err, &noMatch) {
|
||||
t.Fatalf("open = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || !bytes.Equal(got, secret) {
|
||||
t.Fatalf("open = %q, %v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func identity(t *testing.T) *age.X25519Identity {
|
||||
t.Helper()
|
||||
id, err := age.GenerateX25519Identity()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
// Package store holds the connectors module's SQL: the accepted connector
|
||||
// specs the host starts at boot.
|
||||
// Package store holds the connectors module's SQL: the accepted extensions the
|
||||
// host starts at boot and the sealed credentials they are configured with.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/json/jsontext"
|
||||
json "encoding/json/v2"
|
||||
@@ -23,6 +24,24 @@ type Accepted struct {
|
||||
Egress Strings `db:"egress"`
|
||||
Env Strings `db:"env"`
|
||||
Settings jsontext.Value `db:"settings"`
|
||||
// Contract is ContractConnector or ContractSecretEngine.
|
||||
Contract string `db:"contract"`
|
||||
// Credentials maps a slot to a credential name, as a JSON object.
|
||||
Credentials jsontext.Value `db:"credentials"`
|
||||
}
|
||||
|
||||
// Contracts an accepted package can serve.
|
||||
const (
|
||||
ContractConnector = "connector"
|
||||
ContractSecretEngine = "secretengine"
|
||||
)
|
||||
|
||||
// Credential is a credential's sealed fields.
|
||||
type Credential struct {
|
||||
OrgID string `db:"org_id"`
|
||||
Name string `db:"name"`
|
||||
Kind string `db:"kind"`
|
||||
Sealed []byte `db:"sealed"`
|
||||
}
|
||||
|
||||
// Store is the connectors module's Postgres store.
|
||||
@@ -37,7 +56,7 @@ func New(db *sqlx.DB) *Store { return &Store{db: db} }
|
||||
func (s *Store) List(ctx context.Context, orgID string) ([]Accepted, error) {
|
||||
var out []Accepted
|
||||
if err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT org_id, name, path, sha256, egress, env, settings
|
||||
SELECT org_id, name, path, sha256, egress, env, settings, contract, credentials
|
||||
FROM connectors.accepted WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
||||
return nil, fmt.Errorf("list connectors: %w", err)
|
||||
}
|
||||
@@ -47,16 +66,53 @@ func (s *Store) List(ctx context.Context, orgID string) ([]Accepted, error) {
|
||||
// Upsert records an accepted connector, replacing an earlier acceptance.
|
||||
func (s *Store) Upsert(ctx context.Context, a Accepted) error {
|
||||
if _, err := s.db.NamedExecContext(ctx, `
|
||||
INSERT INTO connectors.accepted (org_id, name, path, sha256, egress, env, settings)
|
||||
VALUES (:org_id, :name, :path, :sha256, :egress, :env, :settings)
|
||||
INSERT INTO connectors.accepted (org_id, name, path, sha256, egress, env, settings, contract, credentials)
|
||||
VALUES (:org_id, :name, :path, :sha256, :egress, :env, :settings, :contract, :credentials)
|
||||
ON CONFLICT (org_id, name) DO UPDATE
|
||||
SET path = EXCLUDED.path, sha256 = EXCLUDED.sha256, egress = EXCLUDED.egress,
|
||||
env = EXCLUDED.env, settings = EXCLUDED.settings, updated_at = now()`, a); err != nil {
|
||||
env = EXCLUDED.env, settings = EXCLUDED.settings, contract = EXCLUDED.contract,
|
||||
credentials = EXCLUDED.credentials, updated_at = now()`, a); err != nil {
|
||||
return fmt.Errorf("accept connector: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Credential returns the named credential; ok is false when there is none.
|
||||
func (s *Store) Credential(ctx context.Context, orgID, name string) (Credential, bool, error) {
|
||||
var c Credential
|
||||
err := s.db.GetContext(ctx, &c, `
|
||||
SELECT org_id, name, kind, sealed FROM connectors.credentials WHERE org_id = $1 AND name = $2`, orgID, name)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Credential{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return Credential{}, false, fmt.Errorf("read credential %q: %w", name, err)
|
||||
}
|
||||
return c, true, nil
|
||||
}
|
||||
|
||||
// Credentials returns an organisation's credentials in name order.
|
||||
func (s *Store) Credentials(ctx context.Context, orgID string) ([]Credential, error) {
|
||||
var out []Credential
|
||||
if err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT org_id, name, kind, sealed FROM connectors.credentials WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
||||
return nil, fmt.Errorf("list credentials: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PutCredential records a credential, replacing an earlier one of that name.
|
||||
func (s *Store) PutCredential(ctx context.Context, c Credential) error {
|
||||
if _, err := s.db.NamedExecContext(ctx, `
|
||||
INSERT INTO connectors.credentials (org_id, name, kind, sealed)
|
||||
VALUES (:org_id, :name, :kind, :sealed)
|
||||
ON CONFLICT (org_id, name) DO UPDATE
|
||||
SET kind = EXCLUDED.kind, sealed = EXCLUDED.sealed, updated_at = now()`, c); err != nil {
|
||||
return fmt.Errorf("put credential %q: %w", c.Name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Strings is a string list stored as a JSON array. Value has a value receiver
|
||||
// so database/sql finds it on a struct field; Scan needs a pointer.
|
||||
type Strings []string //nolint:recvcheck // database/sql's Valuer and Scanner idiom
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package connectors
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
@@ -17,47 +18,79 @@ import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/seal"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
|
||||
)
|
||||
|
||||
// validName is the shape of a connector name: it appears in logs and URLs.
|
||||
var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`)
|
||||
|
||||
// Module runs an organisation's accepted connectors and serves their
|
||||
// Module runs an organisation's accepted connectors and secret engines,
|
||||
// keeps the credentials they are configured with, and serves their
|
||||
// administration.
|
||||
type Module struct {
|
||||
orgID string
|
||||
host *Host
|
||||
store *store.Store
|
||||
log *slog.Logger
|
||||
orgID string
|
||||
host *Host
|
||||
store *store.Store
|
||||
sealer *seal.Sealer
|
||||
log *slog.Logger
|
||||
|
||||
mu sync.RWMutex
|
||||
running map[string]*Connector
|
||||
engines map[string]*Engine
|
||||
failed map[string]string
|
||||
}
|
||||
|
||||
// NewModule returns the connectors module for orgID.
|
||||
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module {
|
||||
return &Module{
|
||||
orgID: orgID, host: NewHost(log), store: store.New(db), log: log,
|
||||
running: map[string]*Connector{}, failed: map[string]string{},
|
||||
}
|
||||
// Sealing is the age identity credentials are sealed with, and the backup
|
||||
// recipients that can also open them.
|
||||
type Sealing struct {
|
||||
Identity string
|
||||
Backups []string
|
||||
}
|
||||
|
||||
// Start launches every accepted connector. A connector that fails to start is
|
||||
// reported by Ready and logged; the others still run.
|
||||
// NewModule returns the connectors module for orgID.
|
||||
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealing Sealing) (*Module, error) {
|
||||
sealer, err := seal.New(sealing.Identity, sealing.Backups)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Module{
|
||||
orgID: orgID, host: NewHost(log), store: store.New(db), sealer: sealer, log: log,
|
||||
running: map[string]*Connector{}, engines: map[string]*Engine{}, failed: map[string]string{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Start launches every accepted secret engine, then every accepted connector,
|
||||
// since a connector's credentials may be resolved through an engine. One that
|
||||
// fails to start is reported by Ready and logged; the others still run.
|
||||
func (m *Module) Start(ctx context.Context) error {
|
||||
accepted, err := m.store.List(ctx, m.orgID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, a := range accepted {
|
||||
for _, a := range ordered(accepted) {
|
||||
// A failure is recorded for Ready and logged; the rest still start.
|
||||
_ = m.launch(ctx, a)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ordered puts secret engines ahead of connectors.
|
||||
func ordered(accepted []store.Accepted) []store.Accepted {
|
||||
out := slices.Clone(accepted)
|
||||
slices.SortStableFunc(out, func(a, b store.Accepted) int {
|
||||
return cmp.Compare(rank(a), rank(b))
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func rank(a store.Accepted) int {
|
||||
if a.Contract == store.ContractSecretEngine {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// Get returns the running connector named name.
|
||||
func (m *Module) Get(name string) (*Connector, bool) {
|
||||
m.mu.RLock()
|
||||
@@ -91,6 +124,11 @@ func (m *Module) Ready(context.Context) error {
|
||||
problems = append(problems, name+": process exited")
|
||||
}
|
||||
}
|
||||
for name := range m.engines {
|
||||
if !m.host.Alive(name) {
|
||||
problems = append(problems, name+": process exited")
|
||||
}
|
||||
}
|
||||
if len(problems) == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -98,12 +136,15 @@ func (m *Module) Ready(context.Context) error {
|
||||
return errors.New(strings.Join(problems, "; "))
|
||||
}
|
||||
|
||||
// Close stops every connector.
|
||||
// Close stops every connector and secret engine.
|
||||
func (m *Module) Close() { m.host.Close() }
|
||||
|
||||
// Routes adds the admin routes, each wrapped in guard.
|
||||
func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) {
|
||||
mux.Handle("PUT /api/connectors/{name}", guard(http.HandlerFunc(m.accept)))
|
||||
mux.Handle("PUT /api/connectors/{name}", guard(m.accept(store.ContractConnector)))
|
||||
mux.Handle("PUT /api/secret-engines/{name}", guard(m.accept(store.ContractSecretEngine)))
|
||||
mux.Handle("PUT /api/credentials/{name}", guard(http.HandlerFunc(m.putCredential)))
|
||||
mux.Handle("GET /api/credentials", guard(http.HandlerFunc(m.listCredentials)))
|
||||
}
|
||||
|
||||
type acceptRequest struct {
|
||||
@@ -112,9 +153,16 @@ type acceptRequest struct {
|
||||
Egress []string `json:"egress"`
|
||||
Env []string `json:"env"`
|
||||
Settings map[string]string `json:"settings"`
|
||||
// Credentials maps each credential slot the package declares to a
|
||||
// credential by name.
|
||||
Credentials map[string]string `json:"credentials"`
|
||||
}
|
||||
|
||||
func (m *Module) accept(w http.ResponseWriter, r *http.Request) {
|
||||
func (m *Module) accept(contract string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) { m.acceptAs(w, r, contract) }
|
||||
}
|
||||
|
||||
func (m *Module) acceptAs(w http.ResponseWriter, r *http.Request, contract string) {
|
||||
name := r.PathValue("name")
|
||||
var req acceptRequest
|
||||
if err := httpjson.Read(r, &req); err != nil {
|
||||
@@ -130,9 +178,14 @@ func (m *Module) accept(w http.ResponseWriter, r *http.Request) {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
slots, err := json.Marshal(req.Credentials, json.FormatNilMapAsNull(false))
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
a := store.Accepted{
|
||||
OrgID: m.orgID, Name: name, Path: req.Path, SHA256: req.SHA256,
|
||||
Egress: req.Egress, Env: req.Env, Settings: settings,
|
||||
Egress: req.Egress, Env: req.Env, Settings: settings, Contract: contract, Credentials: slots,
|
||||
}
|
||||
if err := m.store.Upsert(r.Context(), a); err != nil {
|
||||
httpjson.Error(w, http.StatusInternalServerError, err.Error())
|
||||
@@ -145,7 +198,7 @@ func (m *Module) accept(w http.ResponseWriter, r *http.Request) {
|
||||
httpjson.Write(w, http.StatusOK, map[string]string{"name": name, "state": "running"})
|
||||
}
|
||||
|
||||
// launch starts or restarts one accepted connector and records the outcome.
|
||||
// launch starts or restarts one accepted extension and records the outcome.
|
||||
func (m *Module) launch(ctx context.Context, a store.Accepted) error {
|
||||
var settings map[string]string
|
||||
if len(a.Settings) > 0 {
|
||||
@@ -153,10 +206,27 @@ func (m *Module) launch(ctx context.Context, a store.Accepted) error {
|
||||
return m.fail(ctx, a.Name, fmt.Errorf("settings: %w", err))
|
||||
}
|
||||
}
|
||||
c, err := m.host.Start(ctx, Spec{
|
||||
secrets, err := m.secrets(ctx, a)
|
||||
if err != nil {
|
||||
return m.fail(ctx, a.Name, err)
|
||||
}
|
||||
spec := Spec{
|
||||
Name: a.Name, Path: a.Path, SHA256: a.SHA256,
|
||||
Env: a.Env, Egress: a.Egress, Settings: settings,
|
||||
})
|
||||
Env: a.Env, Egress: a.Egress, Settings: settings, Secrets: secrets,
|
||||
}
|
||||
if a.Contract == store.ContractSecretEngine {
|
||||
e, err := m.host.StartEngine(ctx, spec)
|
||||
if err != nil {
|
||||
return m.fail(ctx, a.Name, err)
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.engines[a.Name] = e
|
||||
delete(m.failed, a.Name)
|
||||
m.mu.Unlock()
|
||||
m.log.InfoContext(ctx, "secret engine started", "engine", a.Name)
|
||||
return nil
|
||||
}
|
||||
c, err := m.host.Start(ctx, spec)
|
||||
if err != nil {
|
||||
return m.fail(ctx, a.Name, err)
|
||||
}
|
||||
@@ -171,8 +241,9 @@ func (m *Module) launch(ctx context.Context, a store.Accepted) error {
|
||||
func (m *Module) fail(ctx context.Context, name string, err error) error {
|
||||
m.mu.Lock()
|
||||
delete(m.running, name)
|
||||
delete(m.engines, name)
|
||||
m.failed[name] = err.Error()
|
||||
m.mu.Unlock()
|
||||
m.log.ErrorContext(ctx, "connector failed to start", "connector", name, "error", err)
|
||||
m.log.ErrorContext(ctx, "extension failed to start", "extension", name, "error", err)
|
||||
return err
|
||||
}
|
||||
Reference in new issue
Block a user