Files
archie/modules/connectors/credentials.go
T

474 lines
16 KiB
Go

package connectors
import (
"cmp"
"context"
json "encoding/json/v2"
"errors"
"fmt"
"maps"
"net/http"
"slices"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"golang.org/x/crypto/ssh"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"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" writeOnly:"true"`
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
case "basic":
return []string{"username", "password"}, nil, true
case "bearer":
return []string{"token"}, nil, true
}
return nil, nil, false
}
// credentialKinds is every kind kindFields accepts, in the order a form
// offers them.
var credentialKinds = []string{"bearer", "basic", "machine", "age"}
type credentialKind struct {
Kind string `json:"kind"`
Required []string `json:"required"`
Optional []string `json:"optional,omitzero"`
}
// listCredentialKinds serves kindFields, so a form asks for exactly the fields
// a put accepts.
func listCredentialKinds(context.Context, *struct{}) (*httpapi.Reply[[]credentialKind], error) {
kinds := make([]credentialKind, 0, len(credentialKinds))
for _, kind := range credentialKinds {
required, optional, _ := kindFields(kind)
kinds = append(kinds, credentialKind{Kind: kind, Required: required, Optional: optional})
}
return httpapi.OK(kinds), nil
}
type credentialRequest struct {
Kind string `json:"kind"`
Fields map[string]Field `json:"fields"`
// Scope is who owns the credential. A credential resolves like an
// installation: the person's, then the organisation's, then the instance's.
Scope string `json:"scope,omitzero" enum:"instance,org,person" doc:"Who owns the credential. Default: instance"`
}
type credentialInput struct {
Name string `path:"name" doc:"Lowercase letters, digits and hyphens"`
Body credentialRequest
}
// credentialSaved names a stored credential and the extensions restarted to
// pick it up.
type credentialSaved struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
Scope string `json:"scope" enum:"instance,org,person"`
Restarted []string `json:"restarted"`
}
// credentialView shows where each field comes from, never a value.
type credentialView struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
Scope string `json:"scope" enum:"instance,org,person"`
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(ctx context.Context, in *credentialInput) (*httpapi.Reply[credentialSaved], error) {
name, req := in.Name, in.Body
if !validName.MatchString(name) {
return nil, huma.NewError(http.StatusBadRequest, "a credential needs a lowercase name")
}
if err := checkCredential(req); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
auth, err := authorityOf(ctx)
if err != nil {
return nil, err
}
owner, err := auth.ownerAt(cmp.Or(req.Scope, store.ScopeInstance))
if err != nil {
return nil, err
}
plain, err := json.Marshal(req.Fields)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
sealed, err := m.sealer.Seal(credentialLabel(owner, name, req.Kind), plain)
if err != nil {
m.log.ErrorContext(ctx, "seal credential", "credential", name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't seal the credential")
}
c := store.Credential{Scope: owner.Scope, OrgID: owner.OrgID, PersonID: owner.PersonID, Name: name, Kind: req.Kind, Sealed: sealed}
id, err := m.store.PutCredential(ctx, c)
if err != nil {
m.log.ErrorContext(ctx, "put credential", "credential", name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the credential")
}
restarted, err := m.relaunchUsers(context.WithoutCancel(ctx), owner, name)
if err != nil {
return nil, huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
return httpapi.OK(credentialSaved{ID: id, Name: name, Kind: req.Kind, Scope: owner.Scope, Restarted: restarted}), nil
}
func (m *Module) listCredentials(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]credentialView], error) {
auth, err := authorityOf(ctx)
if err != nil {
return nil, err
}
creds, err := m.store.Credentials(ctx)
if err != nil {
m.log.ErrorContext(ctx, "list credentials", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't list credentials")
}
views := make([]credentialView, 0, len(creds))
for _, c := range creds {
if !auth.sees(c.Owner()) {
continue
}
view, err := m.credentialViewOf(c)
if err != nil {
m.log.ErrorContext(ctx, "open credential", "credential", c.Name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't open credential "+c.Name)
}
views = append(views, view)
}
return httpapi.OK(views), nil
}
func (m *Module) getCredential(ctx context.Context, in *nameInput) (*httpapi.Reply[credentialView], error) {
name := in.Name
c, ok, err := m.credentialFor(ctx, ScopeFromContext(ctx), name)
if err != nil {
m.log.ErrorContext(ctx, "read credential", "credential", name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the credential")
}
if !ok {
return nil, huma.NewError(http.StatusNotFound, "no such credential")
}
view, err := m.credentialViewOf(c)
if err != nil {
m.log.ErrorContext(ctx, "open credential", "credential", name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't open the credential")
}
return httpapi.OK(view), nil
}
// 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{ID: c.ID, Name: c.Name, Kind: c.Kind, Scope: c.Scope, 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
}
// credentialFor finds the credential name resolves to for s: the person's, then
// the organisation's, then the instance's. A credential owned by another
// person or organisation is never returned.
func (m *Module) credentialFor(ctx context.Context, s Scope, name string) (store.Credential, bool, error) {
creds, err := m.store.Credentials(ctx)
if err != nil {
return store.Credential{}, false, err
}
return pickCredential(creds, s, name)
}
func pickCredential(creds []store.Credential, s Scope, name string) (store.Credential, bool, error) {
for _, o := range s.owners() {
for _, c := range creds {
if c.Name == name && c.Owner() == o {
return c, true, nil
}
}
}
return store.Credential{}, false, nil
}
// credentialUsable reports whether s may use credential c: the instance's
// credentials reach every scope, an organisation's only that organisation, and
// a person's only that person.
func credentialUsable(s Scope, c store.Credential) bool {
return slices.Contains(s.owners(), c.Owner())
}
func (m *Module) credentialByID(ctx context.Context, s Scope, id uuid.UUID) (store.Credential, bool, error) {
if id == uuid.Nil {
return store.Credential{}, false, nil
}
creds, err := m.store.Credentials(ctx)
if err != nil {
return store.Credential{}, false, err
}
return pickCredentialByID(creds, s, id)
}
func pickCredentialByID(creds []store.Credential, s Scope, id uuid.UUID) (store.Credential, bool, error) {
if id == uuid.Nil {
return store.Credential{}, false, nil
}
for _, c := range creds {
if c.ID == id && credentialUsable(s, c) {
return c, true, nil
}
}
return store.Credential{}, false, nil
}
// BearerToken returns the token a bearer credential holds, resolved through an
// engine when it names one. The credential resolves for the scope ctx acts for.
// 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.credentialFor(ctx, ScopeFromContext(ctx), name)
if err != nil {
return "", err
}
if !ok {
return "", fmt.Errorf("credential %q doesn't exist", name)
}
return m.resolveBearerToken(ctx, c)
}
// BearerTokenByID returns the token a bearer credential holds, resolved through
// an engine when it names one, provided the credential is usable by the scope
// ctx acts for.
func (m *Module) BearerTokenByID(ctx context.Context, id uuid.UUID) (string, error) {
c, ok, err := m.credentialByID(ctx, ScopeFromContext(ctx), id)
if err != nil {
return "", err
}
if !ok {
return "", fmt.Errorf("credential %s doesn't exist", id)
}
return m.resolveBearerToken(ctx, c)
}
// BearerCredentialName returns the name of the bearer credential id if it
// exists and is usable by the scope ctx acts for.
func (m *Module) BearerCredentialName(ctx context.Context, id uuid.UUID) (string, bool, error) {
c, ok, err := m.credentialByID(ctx, ScopeFromContext(ctx), id)
if err != nil {
return "", false, err
}
if !ok || c.Kind != "bearer" {
return "", false, nil
}
return c.Name, true, nil
}
// BearerCredentialNames returns a map of id to name for every bearer
// credential usable by the scope ctx acts for.
func (m *Module) BearerCredentialNames(ctx context.Context) (map[uuid.UUID]string, error) {
creds, err := m.store.Credentials(ctx)
if err != nil {
return nil, err
}
s := ScopeFromContext(ctx)
out := make(map[uuid.UUID]string)
for _, c := range creds {
if c.Kind == "bearer" && credentialUsable(s, c) {
out[c.ID] = c.Name
}
}
return out, nil
}
func (m *Module) resolveBearerToken(ctx context.Context, c store.Credential) (string, error) {
if c.Kind != "bearer" {
return "", fmt.Errorf("credential %q is not a bearer credential", c.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", c.Name)
}
return m.resolveField(ctx, "", c.Owner(), f)
}
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
}
// credentialLabel binds a sealed credential to its owner, so a row moved to
// another scope no longer opens.
func credentialLabel(o store.Owner, name, kind string) string {
return o.Scope + ":" + o.OrgID + o.PersonID + "/" + name + "/" + kind
}
func (m *Module) openCredential(c store.Credential) (map[string]Field, error) {
plain, err := m.sealer.Open(credentialLabel(c.Owner(), 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 installation's credential slots into the secrets it is
// configured with, keyed "slot.field". Each credential resolves for the
// installation's owner: a person's installation reaches the person's
// credentials and the instance's, an organisation's reaches its own and the
// instance's. 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.Installed) (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.credentialFor(ctx, scopeOf(a.Owner()), 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.Contract, a.Owner(), 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, contract string, owner store.Owner, f Field) (string, error) {
if f.Engine == "" {
return f.Value, nil
}
if contract == store.ContractSecretEngine {
return "", errors.New("a secret engine's own credentials must hold their values")
}
engine, ok := m.engineAt(owner, f.Engine)
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
}
// uses reports whether an installation owned by installOwner may resolve a
// credential owned by credOwner: the instance's credentials reach every
// installation, an organisation's or a person's only their own.
func uses(installOwner, credOwner store.Owner) bool {
return credOwner.Scope == store.ScopeInstance || installOwner == credOwner
}
// relaunchUsers restarts every enabled installation that may resolve the
// credential and has a slot naming it, and returns their names.
func (m *Module) relaunchUsers(ctx context.Context, owner store.Owner, credential string) ([]string, error) {
accepted, err := m.store.List(ctx)
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 || !uses(a.Owner(), owner) || !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...)
}