Compare commits

..
Author SHA1 Message Date
sam 955995fe2b fix(events): connector listener sources pass the delivery policy (#2106)
Every way of storing events now goes through admit, and save takes the
admission it returns. A refused listener batch is dropped and recorded as
a denial, like a refused webhook delivery.
2026-11-22 22:18:11 +11:00
28 changed files with 105 additions and 793 deletions

No files matched your search

-69
View File
@@ -130,12 +130,6 @@ components:
type: string
public_url:
type: string
trusted_proxies:
items:
type: string
type:
- array
- "null"
required:
- public_url
type: object
@@ -1804,18 +1798,11 @@ components:
type: string
public_url:
type: string
trusted_proxies:
items:
type: string
type:
- array
- "null"
required:
- public_url
- oidc_issuer
- oidc_audience
- oidc_client_id
- trusted_proxies
type: object
GovernanceBlackout:
additionalProperties: false
@@ -1833,18 +1820,6 @@ components:
- to
- reason
type: object
GovernanceCandidatesBody:
additionalProperties: false
properties:
identities:
items:
$ref: "#/components/schemas/GovernanceMemberCandidate"
type:
- array
- "null"
required:
- identities
type: object
GovernanceCapabilitiesBody:
additionalProperties: false
properties:
@@ -2033,23 +2008,6 @@ components:
- role
- status
type: object
GovernanceMemberCandidate:
additionalProperties: false
properties:
display_name:
description: Name shown for the identity
type: string
id:
description: Identity ID
type: string
kind:
description: Identity kind
type: string
required:
- id
- kind
- display_name
type: object
GovernanceMembersBody:
additionalProperties: false
properties:
@@ -7118,33 +7076,6 @@ paths:
summary: List the organisation's name changes
tags:
- Organisations
/api/orgs/{id}/member-candidates:
get:
operationId: list-org-member-candidates
parameters:
- description: Organisation ID
in: path
name: id
required: true
schema:
description: Organisation ID
type: string
responses:
"200":
content:
application/json:
schema:
$ref: "#/components/schemas/GovernanceCandidatesBody"
description: OK
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: List active identities that can be added as members
tags:
- Access
/api/orgs/{id}/members:
get:
operationId: list-org-members
-1
View File
@@ -94,7 +94,6 @@ func (o *operations) Start(ctx context.Context) error {
o.allow.UseAuthorizer(checked)
o.tell.UseAccess(checked)
o.hear.UseDeliveryPolicy(governance.RecordingDelivery(access, o.settings, o.log.With("module", "governance")))
o.hear.UseTrustedProxies(o.settings.TrustedProxies)
o.talk.Use(chat.Deps{
People: o.settings, Access: access, Settings: o.settings, Toolbox: o.conns, Judge: o.judge,
Approver: o.allow, Memory: o.remember, Runs: o.engine, Notifier: o.tell,
@@ -1,8 +0,0 @@
-- +goose Up
-- Reverse proxies whose X-Forwarded-For header webhook intake uses as the
-- client address, stored as a JSON array of addresses and CIDR ranges.
ALTER TABLE governance.authentication_settings
ADD COLUMN trusted_proxies jsonb NOT NULL DEFAULT '[]';
-- +goose Down
ALTER TABLE governance.authentication_settings DROP COLUMN trusted_proxies;
+3 -3
View File
@@ -63,8 +63,8 @@ func (c *channelLookups) Get(string) (*connectors.Connector, bool) {
// TestDeliveryIsAuthorizedOnEveryAttempt guards that a queued message is sent
// only while the workload principal may still deliver on its channel. Each
// attempt, including a retry after a backoff or a restart, asks again: a
// revoked grant marks the message failed, and a chain that can't decide leaves
// it queued for its next attempt instead of dropping it.
// revoked grant ends the message as failed, and a chain that can't decide
// leaves it queued for its next attempt instead of dropping it.
func TestDeliveryIsAuthorizedOnEveryAttempt(t *testing.T) {
allowed, revoked, unavailable := governance.Allowed(), governance.DeniedAt(governance.LevelOrg, []string{"org-workload"}), governance.Unavailable()
tests := []struct {
@@ -76,7 +76,7 @@ func TestDeliveryIsAuthorizedOnEveryAttempt(t *testing.T) {
wantOutcomes []string
}{
{name: "an allowed attempt is sent", decisions: []governance.Decision{allowed}, attempts: 1, wantSends: 1, wantOutcomes: []string{"failed: connector \"slack\" isn't running"}},
{name: "a revoked grant fails the message", decisions: []governance.Decision{revoked}, attempts: 1, wantOutcomes: []string{"gave up: " + connectors.ErrRejected.Error() + ": " + governance.ErrDenied.Error() + ": deliver delivery slack"}},
{name: "a revoked grant ends the message", decisions: []governance.Decision{revoked}, attempts: 1, wantOutcomes: []string{"gave up: " + connectors.ErrRejected.Error() + ": " + governance.ErrDenied.Error() + ": deliver delivery slack"}},
{name: "a retry after revocation is refused", decisions: []governance.Decision{allowed, revoked}, attempts: 2, wantSends: 1, wantOutcomes: []string{"failed: connector \"slack\" isn't running", "gave up: " + connectors.ErrRejected.Error() + ": " + governance.ErrDenied.Error() + ": deliver delivery slack"}},
{name: "an undecidable chain leaves the message queued", decisions: []governance.Decision{unavailable}, attempts: 3},
{name: "no policy wired leaves the message queued", unwired: true, attempts: 1},
+19 -23
View File
@@ -1,11 +1,11 @@
// Package deliveries carries what Archie tells people on each channel. It
// holds no approval state: approvals own the request and its answer, and use
// deliveries to carry them. The composer, the chat box in the dashboard, is
// the first channel: its messages are rows a client reads from a cursor, with
// a live stream that only says when to read. Every accepted connector that
// delivers messages is another channel: each gets its own row, retried until
// the connector confirms it, rejects it permanently, or the retry limit is
// reached.
// Package deliveries is the transport for what Archie tells people, on each
// channel. It holds no approval state: approvals own the request and its
// answer, and use deliveries to carry them. The composer, the chat box in the
// dashboard, is the first channel: its messages are rows a client reads from a
// cursor, with a live stream that only says when to read. Every accepted
// connector that delivers messages is another: each gets its own row, retried
// until the connector confirms it, rejects it permanently, or the retry limit
// is reached.
package deliveries
import (
@@ -64,8 +64,8 @@ type Notification struct {
}
// ApprovalRequest is one judged action waiting for a person's answer. It is
// carried like a notification, and adds the approval request an answer refers
// to and when the request expires.
// carried like a notification, with the request an answer names and the time
// it runs out.
type ApprovalRequest struct {
RunID uuid.UUID
RequestID uuid.UUID
@@ -77,8 +77,7 @@ type ApprovalRequest struct {
}
// Message is a composer message as the API shows it. Attempts are the delivery
// attempts recorded on the connector rows that carry the same message, one per
// channel.
// attempts of the connector rows that carry the same message, one per channel.
type Message struct {
Seq int64 `json:"seq"`
ID uuid.UUID `json:"id"`
@@ -109,8 +108,7 @@ type Channels interface {
Get(name string) (*connectors.Connector, bool)
}
// Module delivers one organisation's notifications, approval requests and
// answers.
// Module delivers one organisation's notifications.
type Module struct {
orgID string
store *store.Store
@@ -216,10 +214,9 @@ func (m *Module) send(ctx context.Context, msg store.Message) error {
return nil
}
// SentBy reports whether the channel confirmed a message under any of ids, and
// returns the run that sent it. An id is the identifier a source's event
// carries when it echoes back what Archie sent. The run is empty when no
// message matched.
// SentBy reports whether channel confirmed a message under one of ids, the id
// a source's event carries when it echoes what Archie sent, and the run that
// sent it (nil when the message belonged to none).
func (m *Module) SentBy(ctx context.Context, channel string, ids ...string) (uuid.UUID, bool, error) {
ids = slices.DeleteFunc(slices.Clone(ids), func(id string) bool { return id == "" })
if len(ids) == 0 {
@@ -252,9 +249,9 @@ func (m *Module) Work(ctx context.Context) {
// deliver sends a claimed message when the workload principal may still deliver
// on its channel. Each attempt is decided afresh, so a retry after a backoff or
// a restart honours a revocation made in the meantime. A refusal marks the
// message failed. When the policy chain can't decide, the message stays queued
// for its next attempt.
// a restart honours a revocation made meanwhile. A refusal ends the message as
// failed. When the policy chain can't decide, the message stays queued for its
// next attempt.
func (m *Module) deliver(ctx context.Context, msg store.Message) {
err := governance.RequireWorkload(ctx, m.access, governance.ActionDeliver, governance.Resource{
Kind: governance.KindDelivery, ID: msg.Channel,
@@ -316,8 +313,7 @@ func (m *Module) sendTo(ctx context.Context, msg store.Message) (string, error)
return c.Deliver(ctx, connectors.DeliveryMessage, raw, msg.Key)
}
// backoff returns the wait before the next attempt, given the number of
// attempts made so far.
// backoff is how long to wait after the attempts so far before the next.
func backoff(attempts int) time.Duration {
if attempts >= 10 {
return maxBackoff
+9 -9
View File
@@ -29,8 +29,8 @@ type Message struct {
RequestID uuid.NullUUID `db:"request_id"`
ExpiresAt sql.NullTime `db:"expires_at"`
CreatedAt time.Time `db:"created_at"`
// Sent is set on a message its channel has confirmed. Composer messages
// count as sent as soon as they are stored.
// Sent is set on a message its channel has confirmed; the composer's are
// sent when they are stored.
Sent bool `db:"-"`
Attempts int `db:"attempts"`
}
@@ -93,9 +93,9 @@ func (s *Store) Latest(ctx context.Context, orgID, channel string, limit int) ([
return out, nil
}
// Claim takes the oldest message its channel hasn't confirmed whose next
// attempt is due, and first pushes that attempt out by the backoff. The push
// is the lease, so a crash mid-delivery retries after it rather than never.
// Claim takes the oldest message a channel hasn't confirmed whose next attempt
// is due, and pushes that attempt out by backoff first: the push is the lease,
// so a crash mid-delivery retries after it rather than never.
func (s *Store) Claim(ctx context.Context, backoff func(attempts int) time.Duration) (Message, bool, error) {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
@@ -148,8 +148,8 @@ func (s *Store) Sent(ctx context.Context, seq int64, attempt int, externalID str
`UPDATE deliveries.messages SET sent_at = now(), external_id = $2, last_error = NULL WHERE seq = $1`, externalID)
}
// SentBy finds a message its channel confirmed under any of ids, and returns
// the run that sent it. The run is invalid when the message belonged to none.
// SentBy finds a message its channel confirmed under one of ids. The run is
// the one that sent it, nil when the message belonged to none.
func (s *Store) SentBy(ctx context.Context, orgID, channel string, ids []string) (uuid.NullUUID, bool, error) {
var run uuid.NullUUID
err := s.db.GetContext(ctx, &run, `
@@ -164,8 +164,8 @@ func (s *Store) SentBy(ctx context.Context, orgID, channel string, ids []string)
return run, true, nil
}
// Failed records why an attempt failed, along with the attempt that failed.
// The lease that Claim set still decides when the next attempt is due.
// Failed records why an attempt failed, with the attempt that failed; the
// lease already set when it is tried again.
func (s *Store) Failed(ctx context.Context, seq int64, attempt int, reason string, took time.Duration) error {
return s.attempt(ctx, seq, attempt, attemptOutcome{failure: reason, took: took},
`UPDATE deliveries.messages SET last_error = $2 WHERE seq = $1`, reason)
-74
View File
@@ -1,74 +0,0 @@
package events
import (
"context"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/events/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
)
// TestIntakeEvaluatesThePolicyAgainstTheClientBehindTrustedProxies guards the
// address passed to the delivery policy: X-Forwarded-For is used only when the
// peer is a configured proxy, and is read from right to left past trusted
// hops, so a client can neither hide behind the proxy's address nor spoof one.
func TestIntakeEvaluatesThePolicyAgainstTheClientBehindTrustedProxies(t *testing.T) {
proxies := []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8"), netip.MustParsePrefix("192.0.2.1/32")}
tests := []struct {
name string
peer string
headers []string
trusted []netip.Prefix
readErr error
want string
}{
{name: "no proxies configured uses the peer", peer: "203.0.113.9:4711", want: "203.0.113.9"},
{name: "a direct client can't forge a forwarded address", peer: "203.0.113.9:4711", headers: []string{"198.51.100.7"}, trusted: proxies, want: "203.0.113.9"},
{name: "a trusted proxy reports the client", peer: "10.0.0.5:4711", headers: []string{"198.51.100.7"}, trusted: proxies, want: "198.51.100.7"},
{name: "a forged entry left of the real client is ignored", peer: "10.0.0.5:4711", headers: []string{"1.2.3.4, 198.51.100.7"}, trusted: proxies, want: "198.51.100.7"},
{name: "a chain of trusted proxies is skipped", peer: "10.0.0.5:4711", headers: []string{"198.51.100.7, 10.0.0.9, 192.0.2.1"}, trusted: proxies, want: "198.51.100.7"},
{name: "multiple header lines are joined into one list", peer: "10.0.0.5:4711", headers: []string{"1.2.3.4", "198.51.100.7"}, trusted: proxies, want: "198.51.100.7"},
{name: "a trusted proxy with no header uses the peer", peer: "10.0.0.5:4711", trusted: proxies, want: "10.0.0.5"},
{name: "an unreadable entry uses the peer", peer: "10.0.0.5:4711", headers: []string{"198.51.100.7, unknown"}, trusted: proxies, want: "10.0.0.5"},
{name: "an unreadable proxy list uses the peer", peer: "10.0.0.5:4711", headers: []string{"198.51.100.7"}, readErr: errors.New("store down"), want: "10.0.0.5"},
{name: "an IPv6 client address has no brackets", peer: "10.0.0.5:4711", headers: []string{"2001:db8::7"}, trusted: proxies, want: "2001:db8::7"},
}
const token = "not-a-real-token" //nolint:gosec // fixture bearer token the verifier must accept
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
policy := &deliveryPolicy{decision: governance.Allowed()}
m := &Module{
orgID: "default", log: slog.New(slog.DiscardHandler), inserter: &onceInserter{stored: map[string]bool{}}, deliveries: noEcho{},
reader: fakeSources{store.Source{OrgID: "default", Name: "hook", Connector: "c", Verification: store.Token, TokenSHA256: httpjson.TokenHash(token)}},
parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) {
return []connectors.Event{{Type: "alert", SourceEventID: "evt-1"}}, nil
},
}
m.UseDeliveryPolicy(policy)
m.UseTrustedProxies(func(context.Context) ([]netip.Prefix, error) { return tt.trusted, tt.readErr })
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(`{}`))
req.SetPathValue("source", "hook")
req.RemoteAddr = tt.peer
req.Header.Set("Authorization", "Bearer "+token)
for _, h := range tt.headers {
req.Header.Add("X-Forwarded-For", h)
}
rec := httptest.NewRecorder()
m.intake(rec, req)
if rec.Code != http.StatusAccepted {
t.Fatalf("status %d, want %d", rec.Code, http.StatusAccepted)
}
if want := "org-sys hook " + tt.want; len(policy.asked) != 1 || policy.asked[0] != want {
t.Fatalf("delivery policy asked %v, want %q", policy.asked, want)
}
})
}
}
+17 -77
View File
@@ -18,9 +18,7 @@ import (
"log/slog"
"net"
"net/http"
"net/netip"
"regexp"
"slices"
"strings"
"sync"
"time"
@@ -96,7 +94,6 @@ type Module struct {
inserter eventInserter
types typeReader
delivery governance.DeliveryAuthorizer
proxies func(context.Context) ([]netip.Prefix, error)
sealer Sealer
parse func(ctx context.Context, connector string, body []byte, headers map[string]string) ([]connectors.Event, error)
connectors Connectors
@@ -158,7 +155,7 @@ func (m *Module) intake(w http.ResponseWriter, r *http.Request) {
// delivery is a webhook delivery that passed verification and was parsed.
type delivery struct {
src store.Source
// admission is set after the source's delivery policy allows the sender.
// admission is set once the source's delivery policy allowed the sender.
admission admission
events []connectors.Event
body []byte
@@ -245,18 +242,16 @@ var (
errDeliveryUnavailable = errors.New("delivery policy unavailable")
)
// admission records that the source's delivery policy allowed a sender. Only
// admit creates one and save requires one, so no intake path can store events
// without evaluating the policy.
// admission is a sender the source's delivery policy allowed. Only admit makes
// one and save requires one, so every way of accepting events asks the policy.
type admission struct {
src store.Source
}
// admit evaluates the source's delivery policy against the sender's address.
// The address is empty for a source without a remote sender, such as a
// connector's listener stream. Verified deliveries are evaluated too. If the
// policy chain returns no decision, admit returns 503 so that a webhook sender
// retries, and nothing is stored.
// admit applies the source's delivery policy to the sender's address, which is
// empty for a source that has no remote sender, such as a connector's listener
// stream. A verified delivery still needs it. When the policy chain can't
// decide, the status is 503 so a webhook sender retries and nothing is stored.
func (m *Module) admit(ctx context.Context, src store.Source, addr string) (admission, int, error) {
if m.delivery == nil {
return admission{}, http.StatusServiceUnavailable, errDeliveryUnavailable
@@ -275,67 +270,13 @@ func (m *Module) admit(ctx context.Context, src store.Source, addr string) (admi
return admission{}, http.StatusForbidden, errDeliveryDenied
}
// clientAddr returns the request's client address: the connection's peer
// address, or the forwarded client address when the peer is a trusted proxy.
func (m *Module) clientAddr(ctx context.Context, r *http.Request) string {
peer := r.RemoteAddr
if host, _, err := net.SplitHostPort(peer); err == nil {
peer = host
}
return forwardedClient(peer, r.Header.Values("X-Forwarded-For"), m.trustedProxies(ctx))
}
// forwardedClient returns the client address from X-Forwarded-For. The header
// lists the client first, followed by each proxy that relayed the request.
// Only entries appended by trusted proxies are reliable, because a client can
// set any value at the left end, so the list is read from right to left and
// the first address that is not a trusted proxy is returned. The peer address
// is returned when the peer is not trusted or the header can't be parsed.
func forwardedClient(peer string, forwarded []string, trusted []netip.Prefix) string {
if len(trusted) == 0 || !isTrusted(peer, trusted) {
return peer
}
hops := strings.Split(strings.Join(forwarded, ","), ",")
for i, hop := range slices.Backward(hops) {
hop := strings.TrimSpace(hop)
addr, err := netip.ParseAddr(hop)
if err != nil {
return peer
}
if i == 0 || !isTrusted(hop, trusted) {
return addr.Unmap().String()
}
}
return peer
}
// isTrusted reports whether addr is inside any of the trusted prefixes.
func isTrusted(addr string, trusted []netip.Prefix) bool {
a, err := netip.ParseAddr(addr)
// clientAddr is the address a request came from, without its port.
func (m *Module) clientAddr(_ context.Context, r *http.Request) string {
addr, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return false
return r.RemoteAddr
}
a = a.Unmap()
return slices.ContainsFunc(trusted, func(p netip.Prefix) bool { return p.Contains(a) })
}
// trustedProxies returns the configured trusted proxy prefixes.
func (m *Module) trustedProxies(ctx context.Context) []netip.Prefix {
if m.proxies == nil {
return nil
}
prefixes, err := m.proxies(ctx)
if err != nil {
m.log.WarnContext(ctx, "read trusted proxies", "error", err)
return nil
}
return prefixes
}
// UseTrustedProxies sets the function that reads the trusted reverse proxies.
// If it is not set, X-Forwarded-For is ignored.
func (m *Module) UseTrustedProxies(read func(context.Context) ([]netip.Prefix, error)) {
m.proxies = read
return addr
}
// parseWith has a running connector parse a delivery.
@@ -461,12 +402,11 @@ func (m *Module) listenBatch(ctx context.Context, src store.Source, events []con
return m.store.SetCursor(ctx, m.orgID, src.Name, next)
}
// storeListened stores a batch streamed by a connector listener if the source's
// delivery policy allows it. A listener has no remote sender, so the policy is
// evaluated with an empty address: rules on the source apply, and a rule that
// allows only specific addresses denies every listener. A denied batch is
// dropped without an error, because evaluating it again would return the same
// decision.
// storeListened stores a batch a listening connector streamed, once the
// source's delivery policy allows it. A listener has no remote sender, so the
// policy sees no address: rules on the source apply, and a rule that admits
// only some addresses admits no listener. A refused batch is dropped and
// not an error, since asking again would get the same answer.
func (m *Module) storeListened(ctx context.Context, src store.Source, events []connectors.Event) error {
adm, _, err := m.admit(ctx, src, "")
if errors.Is(err, errDeliveryDenied) {
+5 -5
View File
@@ -10,10 +10,10 @@ import (
)
// TestListenedEventsPassTheDeliveryPolicyBeforeStoring guards connector
// listener intake: a streamed batch is evaluated against its source's delivery
// policy, as a webhook delivery is. A denial stores nothing and does not fail
// the stream, so the cursor advances. An unavailable decision fails the stream
// so that the batch is fetched again.
// listener intake: a streamed batch is checked against its source's delivery
// policy like a webhook delivery. A refusal stores nothing and doesn't fail
// the stream, so the cursor moves on, while an undecidable policy fails it so
// the batch is fetched again.
func TestListenedEventsPassTheDeliveryPolicyBeforeStoring(t *testing.T) {
tests := []struct {
name string
@@ -24,7 +24,7 @@ func TestListenedEventsPassTheDeliveryPolicyBeforeStoring(t *testing.T) {
}{
{name: "an allowed batch is stored", policy: governance.Allowed(), wantStored: 1},
{name: "a denied batch is dropped without failing the stream", policy: governance.DeniedAt(governance.LevelObject, []string{"tg-deny"})},
{name: "an unavailable decision fails the stream so the batch is fetched again", policy: governance.Unavailable(), wantErr: true},
{name: "an undecidable policy fails the stream so the batch is fetched again", policy: governance.Unavailable(), wantErr: true},
{name: "no policy wired fails the stream", unwired: true, wantErr: true},
}
for _, tt := range tests {
+6 -41
View File
@@ -125,7 +125,7 @@ func TestPendingChainRefusesUntilLoaded(t *testing.T) {
if !loaded {
return nil, errors.New("store down")
}
return ShippedOrgPolicies(DefaultOrgID), nil
return nil, nil
}, slog.New(slog.DiscardHandler))
request := func() Decision {
@@ -199,20 +199,17 @@ func TestLiveAppliesAPolicyEditBeforeTheNextDecision(t *testing.T) {
}{
{
name: "an unchanged version keeps the chain",
write: func(store *fakePolicyStore) { store.policies = append(ShippedOrgPolicies(DefaultOrgID), forbidAll) },
write: func(store *fakePolicyStore) { store.policies = []Policy{forbidAll} },
wantAllowed: true,
},
{
name: "a bumped version applies the forbid",
write: func(store *fakePolicyStore) {
store.policies = append(ShippedOrgPolicies(DefaultOrgID), forbidAll)
store.version++
},
name: "a bumped version applies the forbid",
write: func(store *fakePolicyStore) { store.policies = []Policy{forbidAll}; store.version++ },
},
{
name: "a failed version read refuses",
write: func(store *fakePolicyStore) {
store.policies = append(ShippedOrgPolicies(DefaultOrgID), forbidAll)
store.policies = []Policy{forbidAll}
store.version++
store.versionErr = storeDown
},
@@ -226,7 +223,7 @@ func TestLiveAppliesAPolicyEditBeforeTheNextDecision(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
store := &fakePolicyStore{version: 1, policies: ShippedOrgPolicies(DefaultOrgID)}
store := &fakePolicyStore{version: 1}
live := NewPending(store.PoliciesVersion, store.ListPolicies, slog.New(slog.DiscardHandler))
if err := live.Reload(t.Context()); err != nil {
t.Fatal(err)
@@ -499,35 +496,3 @@ func TestSeedShippedPolicies(t *testing.T) {
t.Fatal("a failed seed returned no error")
}
}
// TestAuthorizeWithoutOrgPolicies guards deny by default: an org with no
// org-level policies, even with instance or workspace policies present, must
// deny every request instead of falling through to allow.
func TestAuthorizeWithoutOrgPolicies(t *testing.T) {
const org = OrgID("acme")
owner := Principal{IdentityID: "o", Org: org, Memberships: []Membership{{IdentityID: "o", OrgID: org, Role: RoleOwner}}}
permitAllInstance := Policy{ID: "all", Level: LevelInstance, Text: `permit(principal, action, resource);`}
spaceOnly := Policy{
ID: "space", Level: LevelWorkspace, OrgID: org, WorkspaceID: "prod",
Text: `permit(principal, action, resource);`,
}
tests := []struct {
name string
policies []Policy
allowed bool
}{
{name: "no policies at all"},
{name: "another org is seeded", policies: ShippedOrgPolicies(DefaultOrgID)},
{name: "instance policy only", policies: []Policy{permitAllInstance}},
{name: "workspace policy only", policies: []Policy{spaceOnly}},
{name: "shipped org policies", policies: ShippedOrgPolicies(org), allowed: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := NewEngine(tt.policies).Authorize(t.Context(), owner, ActionRead, Resource{Kind: KindDashboard, Org: org}, AccessContext{})
if got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
}
})
}
}
+5 -6
View File
@@ -333,11 +333,10 @@ func (m *Module) getAuthentication(ctx context.Context, _ *struct{}) (*httpapi.R
type authenticationInput struct {
Session string `cookie:"archie_session"`
Body struct {
PublicURL string `json:"public_url"`
OIDCIssuer string `json:"oidc_issuer,omitempty"`
OIDCAudience string `json:"oidc_audience,omitempty"`
OIDCClientID string `json:"oidc_client_id,omitempty"`
TrustedProxies []string `json:"trusted_proxies,omitempty"`
PublicURL string `json:"public_url"`
OIDCIssuer string `json:"oidc_issuer,omitempty"`
OIDCAudience string `json:"oidc_audience,omitempty"`
OIDCClientID string `json:"oidc_client_id,omitempty"`
}
}
@@ -347,7 +346,7 @@ func (m *Module) putAuthentication(ctx context.Context, in *authenticationInput)
}
err := m.SaveAuthenticationSettings(ctx, AuthenticationSettings(in.Body))
if errors.Is(err, ErrInvalidIdentity) {
return nil, huma.Error400BadRequest("Use a valid instance origin, trusted proxies that are addresses or CIDR ranges, and complete OIDC settings. Remove enrolled passkeys before changing the instance URL.")
return nil, huma.Error400BadRequest("Use a valid instance origin and complete OIDC settings. Remove enrolled passkeys before changing the instance URL.")
}
if err != nil {
return nil, m.accountError(ctx, err)
+3 -3
View File
@@ -118,9 +118,9 @@ type recordingDelivery struct {
log *slog.Logger
}
// RecordingDelivery wraps a so that every denied delivery is stored as a
// denial, for webhook and listener intake alike. An unavailable decision is
// not a denial and is not stored.
// RecordingDelivery wraps a so every refused delivery is stored as a denial,
// whichever way the event arrived. A decision that could not be made is not a
// denial and is not stored.
func RecordingDelivery(a DeliveryAuthorizer, denials DenialRecorder, log *slog.Logger) DeliveryAuthorizer {
return recordingDelivery{DeliveryAuthorizer: a, denials: denials, log: log}
}
-6
View File
@@ -180,12 +180,6 @@ func (e *Engine) Authorize(_ context.Context, p Principal, a Action, r Resource,
if p.Org == "" || resOrg != p.Org {
return DeniedAt(LevelInstance, []string{CrossOrgForbidID})
}
// Only org-level policies grant access within an org. evaluate skips empty
// levels, so without this check an org with no org-level policies would be
// allowed.
if !e.orgs[resOrg].active() {
return DeniedAt(LevelOrg, nil)
}
return evaluate(e.chain(p, r), buildEntities(p, r), buildRequest(p, a, r, c))
}
+2 -10
View File
@@ -433,27 +433,19 @@ type AccountSecurity interface {
RecoverAccount(ctx context.Context, email, code, password string) error
}
// AuthenticationSettings stores the instance's public origin, its trusted
// reverse proxies and the OIDC parameters.
// AuthenticationSettings stores instance public origin and OIDC parameters.
type AuthenticationSettings struct {
PublicURL string `json:"public_url"`
OIDCIssuer string `json:"oidc_issuer"`
OIDCAudience string `json:"oidc_audience"`
OIDCClientID string `json:"oidc_client_id"`
// TrustedProxies are the addresses and CIDR ranges of reverse proxies whose
// X-Forwarded-For header webhook intake uses as the client address.
TrustedProxies []string `json:"trusted_proxies"`
}
// Validate checks that PublicURL is a valid origin, the trusted proxies are
// addresses or ranges, and OIDC fields are paired.
// Validate checks that PublicURL is a valid origin and OIDC fields are paired.
func (s AuthenticationSettings) Validate() error {
if !validInstanceOrigin(s.PublicURL) {
return ErrInvalidIdentity
}
if _, err := normalizeProxies(s.TrustedProxies); err != nil {
return err
}
if s.OIDCIssuer == "" {
if s.OIDCClientID != "" || s.OIDCAudience != "" {
return ErrInvalidIdentity
@@ -29,8 +29,6 @@ type AuthSettingsRow struct {
OIDCIssuer string `db:"oidc_issuer"`
OIDCAudience string `db:"oidc_audience"`
OIDCClientID string `db:"oidc_client_id"`
// TrustedProxies is a JSON array of addresses and CIDR ranges.
TrustedProxies []byte `db:"trusted_proxies"`
}
// RegisterAccountParams carries the validated inputs to create a user account.
@@ -344,7 +342,7 @@ func (s *Store) RecoverAccount(ctx context.Context, email, recoveryHash, newPass
func (s *Store) AuthenticationSettings(ctx context.Context) (AuthSettingsRow, error) {
var out AuthSettingsRow
err := s.db.GetContext(ctx, &out, `
SELECT public_url, oidc_issuer, oidc_audience, oidc_client_id, trusted_proxies
SELECT public_url, oidc_issuer, oidc_audience, oidc_client_id
FROM governance.authentication_settings WHERE singleton`)
if errors.Is(err, sql.ErrNoRows) {
return AuthSettingsRow{}, nil
@@ -359,9 +357,9 @@ func (s *Store) AuthenticationSettings(ctx context.Context) (AuthSettingsRow, er
func (s *Store) SaveAuthenticationSettings(ctx context.Context, row AuthSettingsRow) (updated bool, err error) {
res, err := s.db.ExecContext(ctx, `
UPDATE governance.authentication_settings
SET public_url = $1, oidc_issuer = $2, oidc_audience = $3, oidc_client_id = $4, trusted_proxies = $5
SET public_url = $1, oidc_issuer = $2, oidc_audience = $3, oidc_client_id = $4
WHERE singleton AND (public_url = $1 OR NOT EXISTS (SELECT 1 FROM governance.passkeys))`,
row.PublicURL, row.OIDCIssuer, row.OIDCAudience, row.OIDCClientID, string(row.TrustedProxies))
row.PublicURL, row.OIDCIssuer, row.OIDCAudience, row.OIDCClientID)
if err != nil {
return false, fmt.Errorf("save authentication settings: %w", err)
}
-42
View File
@@ -20,7 +20,6 @@ type memberDirectory interface {
EnsureMembership(context.Context, Membership) error
RemoveMembership(context.Context, Membership) error
Get(context.Context, IdentityID) (Identity, error)
ListInstanceIdentities(context.Context) ([]Identity, error)
Apply(context.Context, IdentityID, int64, IdentityCommand, IdentityAudit) (Identity, error)
}
@@ -52,17 +51,6 @@ type membersBody struct {
Members []Member `json:"members"`
}
// memberCandidate is the part of an identity needed to choose it as a member.
type memberCandidate struct {
ID IdentityID `json:"id" doc:"Identity ID"`
Kind Kind `json:"kind" doc:"Identity kind"`
DisplayName string `json:"display_name" doc:"Name shown for the identity"`
}
type candidatesBody struct {
Identities []memberCandidate `json:"identities"`
}
type membershipBody struct {
Membership Membership `json:"membership"`
}
@@ -110,7 +98,6 @@ func (m *Module) RegisterAccess(api huma.API) {
}
a := m.members()
httpapi.Register(api, httpapi.Authorized(ActionRead, KindMember), op("list-org-members", http.MethodGet, "/api/orgs/{id}/members", "List an organisation's members", 0), a.list)
httpapi.Register(api, httpapi.Authorized(ActionManageMembers, KindMember), op("list-org-member-candidates", http.MethodGet, "/api/orgs/{id}/member-candidates", "List active identities that can be added as members", 0), a.candidates)
httpapi.Register(api, httpapi.Authorized(ActionManageMembers, KindMember), op("add-org-member", http.MethodPost, "/api/orgs/{id}/members", "Add a person by email or provider subject", http.StatusCreated), a.add)
httpapi.Register(api, httpapi.Authorized(ActionManageMembers, KindMember), op("set-org-member", http.MethodPut, "/api/orgs/{id}/members/{identity}", "Give a member a role", 0), a.set)
httpapi.Register(api, httpapi.Authorized(ActionManageMembers, KindMember), op("remove-org-member", http.MethodDelete, "/api/orgs/{id}/members/{identity}", "Remove a membership", http.StatusNoContent), a.remove)
@@ -131,35 +118,6 @@ func (a *memberAPI) list(ctx context.Context, in *orgPath) (*httpapi.Reply[membe
return httpapi.OK(membersBody{Members: values}), nil
}
// candidates lists the instance's active identities that have no
// organisation-wide membership. These are the identities offered when adding a
// member.
// The system identity is excluded because it cannot be a member.
func (a *memberAPI) candidates(ctx context.Context, in *orgPath) (*httpapi.Reply[candidatesBody], error) {
if _, err := actingOrg(ctx, OrgID(in.ID)); err != nil {
return nil, err
}
members, err := a.dir.ListMembers(ctx, OrgID(in.ID))
if err != nil {
return nil, a.failed(ctx, "read the members", err)
}
all, err := a.dir.ListInstanceIdentities(ctx)
if err != nil {
return nil, a.failed(ctx, "read the identities", err)
}
out := make([]memberCandidate, 0, len(all))
for _, value := range all {
if value.Kind == KindSystem || value.Lifecycle != LifecycleActive {
continue
}
if _, held := roleHeld(members, value.ID, ""); held {
continue
}
out = append(out, memberCandidate{ID: value.ID, Kind: value.Kind, DisplayName: value.DisplayName})
}
return httpapi.OK(candidatesBody{Identities: out}), nil
}
func (a *memberAPI) set(ctx context.Context, in *setMemberInput) (*httpapi.Reply[membershipBody], error) {
org, target := OrgID(in.ID), IdentityID(in.Identity)
p, err := actingOrg(ctx, org)
+4 -66
View File
@@ -5,7 +5,6 @@ import (
"errors"
"log/slog"
"net/http"
"slices"
"strings"
"testing"
@@ -16,9 +15,8 @@ import (
// fakeDirectory records the changes a member route lets through.
type fakeDirectory struct {
members []Member
identities []Identity
changes []string
members []Member
changes []string
}
func (f *fakeDirectory) ListMembers(context.Context, OrgID) ([]Member, error) { return f.members, nil }
@@ -37,10 +35,6 @@ func (f *fakeDirectory) Get(_ context.Context, id IdentityID) (Identity, error)
return Identity{ID: id, Version: 1}, nil
}
func (f *fakeDirectory) ListInstanceIdentities(context.Context) ([]Identity, error) {
return f.identities, nil
}
func (f *fakeDirectory) Apply(_ context.Context, id IdentityID, _ int64, c IdentityCommand, _ IdentityAudit) (Identity, error) {
f.changes = append(f.changes, string(c.Type)+" "+string(id))
return Identity{ID: id}, nil
@@ -89,7 +83,6 @@ func TestAccessWritesNeedTheirGrant(t *testing.T) {
writes := 0
for _, route := range httpapi.Routes(api) {
mutates := route.Method != http.MethodGet
candidates := route.ID == "list-org-member-candidates"
action, kind, ok := route.Access.Declared()
if !ok {
t.Errorf("%s declares no access", route.ID)
@@ -102,7 +95,7 @@ func TestAccessWritesNeedTheirGrant(t *testing.T) {
if strings.HasPrefix(route.Path, "/api/access/policies") {
wantAction = string(ActionManagePolicies)
}
if (mutates || candidates) && action != wantAction {
if mutates && action != wantAction {
t.Errorf("%s declares %q, want %q", route.ID, action, wantAction)
}
if !mutates && route.Path == "/api/access/denials" && action != string(ActionReadAudit) {
@@ -112,7 +105,7 @@ func TestAccessWritesNeedTheirGrant(t *testing.T) {
if !engine.Authorize(t.Context(), actor("admin", RoleAdmin), Action(action), resource, AccessContext{}).Allowed {
t.Errorf("%s: an admin is refused %s %s", route.ID, action, kind)
}
if mutates || candidates || route.Path == "/api/access/denials" {
if mutates || route.Path == "/api/access/denials" {
for _, role := range []Role{RoleViewer, RoleDeveloper} {
if engine.Authorize(t.Context(), actor("lowly", role), Action(action), resource, AccessContext{}).Allowed {
t.Errorf("%s: a %s is allowed %s %s", route.ID, role, action, kind)
@@ -125,61 +118,6 @@ func TestAccessWritesNeedTheirGrant(t *testing.T) {
}
}
// TestMemberCandidates guards the listing offered when adding a member: it is
// limited to active identities outside the organisation, never reaches another
// organisation, and never offers the system identity.
func TestMemberCandidates(t *testing.T) {
identities := []Identity{
{ID: "root", Kind: KindUser, DisplayName: "Root", Lifecycle: LifecycleActive},
{ID: "newcomer", Kind: KindUser, DisplayName: "Newcomer", Lifecycle: LifecycleActive},
{ID: "scoped", Kind: KindUser, DisplayName: "Scoped", Lifecycle: LifecycleActive},
{ID: "gone", Kind: KindUser, DisplayName: "Gone", Lifecycle: LifecycleSuspended},
{ID: SystemID, Kind: KindSystem, DisplayName: "System", Lifecycle: LifecycleActive},
}
members := []Member{
member("root", RoleOwner, LifecycleActive),
{IdentityID: "scoped", Kind: KindUser, WorkspaceID: "ws", Role: RoleViewer, Status: LifecycleActive},
}
foreign := actor("outsider", RoleOwner)
foreign.Org = "other"
foreign.Memberships = []Membership{{IdentityID: "outsider", OrgID: "other", Role: RoleOwner}}
tests := []struct {
name string
by *Principal
org OrgID
want int
ids []IdentityID
}{
{"owner sees identities outside the org", new(actor("root", RoleOwner)), DefaultOrgID, http.StatusOK, []IdentityID{"newcomer", "scoped"}},
{"member of another org", &foreign, DefaultOrgID, http.StatusNotFound, nil},
{"owner of another org asks for its own org", &foreign, "other", http.StatusOK, []IdentityID{"newcomer", "scoped"}},
{"caller without a session", nil, DefaultOrgID, http.StatusUnauthorized, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dir := &fakeDirectory{members: members, identities: identities}
ctx := t.Context()
if tt.by != nil {
ctx = WithPrincipal(ctx, *tt.by)
}
reply, err := memberRoutes(dir).candidates(ctx, &orgPath{ID: string(tt.org)})
if got := status(t, err); got != tt.want {
t.Fatalf("status = %d (%v), want %d", got, err, tt.want)
}
if err != nil {
return
}
var got []IdentityID
for _, c := range reply.Body.Identities {
got = append(got, c.ID)
}
if !slices.Equal(got, tt.ids) {
t.Fatalf("candidates = %v, want %v", got, tt.ids)
}
})
}
}
// TestLastOwnerIsKept guards the rule that an organisation always keeps an
// active owner: removing, demoting or suspending the only one is refused before
// anything changes.
+1 -1
View File
@@ -35,7 +35,7 @@ func (o *oidcLogin) flow(ctx context.Context, settings AuthenticationSettingsSto
}
o.mu.Lock()
defer o.mu.Unlock()
if o.provider == nil || o.current.OIDCIssuer != value.OIDCIssuer || o.current.OIDCAudience != value.OIDCAudience {
if o.provider == nil || o.current != value {
provider, err := newOIDCProvider(value.OIDCIssuer, value.OIDCAudience)
if err != nil {
return nil, err
-81
View File
@@ -1,81 +0,0 @@
package governance
import (
"context"
json "encoding/json/v2"
"fmt"
"net/netip"
"strings"
)
// maxTrustedProxies limits the size of the proxy list, which is read on every
// webhook delivery.
const maxTrustedProxies = 64
// normalizeProxies trims each entry and checks that it is an address or a CIDR
// range. A bare address means that one host.
func normalizeProxies(entries []string) ([]string, error) {
if len(entries) > maxTrustedProxies {
return nil, ErrInvalidIdentity
}
out := make([]string, 0, len(entries))
for _, entry := range entries {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
prefix, err := parseProxy(entry)
if err != nil {
return nil, ErrInvalidIdentity
}
out = append(out, prefix.String())
}
return out, nil
}
func parseProxy(entry string) (netip.Prefix, error) {
if strings.Contains(entry, "/") {
return netip.ParsePrefix(entry)
}
addr, err := netip.ParseAddr(entry)
if err != nil {
return netip.Prefix{}, err
}
return netip.PrefixFrom(addr, addr.BitLen()), nil
}
// TrustedProxies returns the reverse proxies whose X-Forwarded-For header
// webhook intake uses as the client address.
func (m *Module) TrustedProxies(ctx context.Context) ([]netip.Prefix, error) {
settings, err := m.AuthenticationSettings(ctx)
if err != nil {
return nil, err
}
out := make([]netip.Prefix, 0, len(settings.TrustedProxies))
for _, entry := range settings.TrustedProxies {
prefix, err := parseProxy(entry)
if err != nil {
return nil, fmt.Errorf("stored trusted proxy %q: %w", entry, err)
}
out = append(out, prefix)
}
return out, nil
}
func encodeProxies(entries []string) ([]byte, error) {
if entries == nil {
entries = []string{}
}
return json.Marshal(entries)
}
func decodeProxies(raw []byte) ([]string, error) {
entries := []string{}
if len(raw) == 0 {
return entries, nil
}
if err := json.Unmarshal(raw, &entries); err != nil {
return nil, fmt.Errorf("read trusted proxies: %w", err)
}
return entries, nil
}
+8 -36
View File
@@ -115,20 +115,6 @@ func (m *Module) List(ctx context.Context) ([]Identity, error) {
return out, nil
}
// ListInstanceIdentities returns every identity on the instance, regardless of
// the caller's organisation scope.
func (m *Module) ListInstanceIdentities(ctx context.Context) ([]Identity, error) {
rows, err := m.store.ListIdentities(ctx, nil)
if err != nil {
return nil, err
}
out := make([]Identity, 0, len(rows))
for _, r := range rows {
out = append(out, identityFromRow(r))
}
return out, nil
}
// Get returns one identity by ID if visible to the caller's scope.
func (m *Module) Get(ctx context.Context, id IdentityID) (Identity, error) {
row, err := m.store.GetVisibleIdentity(ctx, string(id), scopeOrgFilter(ctx))
@@ -548,16 +534,11 @@ func (m *Module) AuthenticationSettings(ctx context.Context) (AuthenticationSett
if err != nil {
return AuthenticationSettings{}, err
}
proxies, err := decodeProxies(row.TrustedProxies)
if err != nil {
return AuthenticationSettings{}, err
}
return AuthenticationSettings{
PublicURL: row.PublicURL,
TrustedProxies: proxies,
OIDCIssuer: row.OIDCIssuer,
OIDCAudience: row.OIDCAudience,
OIDCClientID: row.OIDCClientID,
PublicURL: row.PublicURL,
OIDCIssuer: row.OIDCIssuer,
OIDCAudience: row.OIDCAudience,
OIDCClientID: row.OIDCClientID,
}, nil
}
@@ -571,20 +552,11 @@ func (m *Module) SaveAuthenticationSettings(ctx context.Context, value Authentic
if err := value.Validate(); err != nil {
return err
}
proxies, err := normalizeProxies(value.TrustedProxies)
if err != nil {
return err
}
encoded, err := encodeProxies(proxies)
if err != nil {
return err
}
updated, err := m.store.SaveAuthenticationSettings(ctx, store.AuthSettingsRow{
PublicURL: value.PublicURL,
TrustedProxies: encoded,
OIDCIssuer: value.OIDCIssuer,
OIDCAudience: value.OIDCAudience,
OIDCClientID: value.OIDCClientID,
PublicURL: value.PublicURL,
OIDCIssuer: value.OIDCIssuer,
OIDCAudience: value.OIDCAudience,
OIDCClientID: value.OIDCClientID,
})
if err != nil {
return err
-5
View File
@@ -144,11 +144,6 @@
"label": "Models",
"description": "The organisation's agent models and aliases."
},
{
"path": "/org/approvals",
"label": "Approvals",
"description": "Default owner, escalation path and approval deadline."
},
{
"path": "/org/instructions",
"label": "Instructions",
+2 -7
View File
@@ -7,16 +7,14 @@ import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import CodeView from "@/base/CodeView.vue";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { api, classifyActionError, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { SettingRow } from "@/components/ui/setting-row";
import { Section } from "@/components/ui/section";
interface Settings {public_url:string;oidc_issuer:string;oidc_audience:string;oidc_client_id:string;trusted_proxies:string[]}
const value=ref<Settings>({public_url:"",oidc_issuer:"",oidc_audience:"",oidc_client_id:"",trusted_proxies:[]});const loaded=ref(false);const error=ref("");const sessionExpired=ref(false);const busy=ref(false);const saved=ref(false);
interface Settings {public_url:string;oidc_issuer:string;oidc_audience:string;oidc_client_id:string}
const value=ref<Settings>({public_url:"",oidc_issuer:"",oidc_audience:"",oidc_client_id:""});const loaded=ref(false);const error=ref("");const sessionExpired=ref(false);const busy=ref(false);const saved=ref(false);
async function load(){try{value.value=await api.authentication<Settings>();loaded.value=true;error.value=""}catch(cause){error.value=describeError(cause, errors.common.unknown)}finally{loaded.value=true}}
onMounted(load);
const proxyText=computed({get:()=>value.value.trusted_proxies.join("\n"),set:(text:string|number)=>{value.value.trusted_proxies=String(text).split("\n")}});
const redirectURI=computed(()=>`${value.value.public_url.replace(/\/$/,"")}/oauth2/callback`);
async function save(){busy.value=true;error.value="";saved.value=false;try{await api.saveAuthentication(value.value);saved.value=true}catch(cause){error.value=describeError(cause, errors.common.unknown);sessionExpired.value=classifyActionError(cause).kind==="session-expired"}finally{busy.value=false}}
</script>
@@ -28,9 +26,6 @@ async function save(){busy.value=true;error.value="";saved.value=false;try{await
<Section title="Instance URL">
<SettingRow label="Public address" for="instance-url" hint="Passkeys require HTTPS and a domain name, or localhost. Once passkeys are enrolled, their domain is fixed."><Input id="instance-url" v-model="value.public_url" type="url" required /></SettingRow>
</Section>
<Section title="Reverse proxies">
<SettingRow label="Trusted proxies" for="trusted-proxies" hint="One address or CIDR range per line. Webhook deliveries from these proxies are checked against the client address in X-Forwarded-For."><Textarea id="trusted-proxies" v-model="proxyText" rows="3" class="max-w-xl font-mono" placeholder="10.0.0.0/8" /></SettingRow>
</Section>
<Section title="OpenID Connect">
<SettingRow label="Issuer URL" for="oidc-issuer"><Input id="oidc-issuer" v-model="value.oidc_issuer" type="url" placeholder="https://identity.example.com" /></SettingRow>
<SettingRow label="Client ID" for="oidc-client"><Input id="oidc-client" v-model="value.oidc_client_id" /></SettingRow>
-22
View File
@@ -288,9 +288,6 @@ export const api = {
credentialKinds: () => request<CredentialKind[]>("/api/credential-kinds"),
putCredential: (name: string, kind: string, fields: Record<string, CredentialField>) =>
request<{ name: string; kind: string; restarted: string[] }>(`/api/credentials/${encodeURIComponent(name)}`, { method: "PUT", body: { kind, fields }, timeoutMs: 60_000 }),
orgSettings: () => request<OrgSettings>("/api/settings"),
putOrgSettings: (settings: OrgSettings) =>
request<OrgSettings>("/api/settings", { method: "PUT", body: settings }),
instructions: () => request<{ text: string }>("/api/settings/instructions"),
saveInstructions: (text: string) =>
request<{ text: string }>("/api/settings/instructions", { method: "PUT", body: { text } }),
@@ -415,8 +412,6 @@ export const api = {
orgAgents: <T = unknown>(id: string) => request<T>(`/api/orgs/${encodeURIComponent(id)}/agents`),
orgMembers: <T = unknown>(id: string) =>
request<T>(`/api/orgs/${encodeURIComponent(id)}/members`),
orgMemberCandidates: <T = unknown>(id: string) =>
request<T>(`/api/orgs/${encodeURIComponent(id)}/member-candidates`),
addOrgMember: <T = unknown>(
id: string,
member: { subject?: string; email?: string; role: string },
@@ -1210,23 +1205,6 @@ export interface ExtensionInput {
effects?: ServerEffects;
}
/** One stop on the escalation path; the deadline is a Go duration string. */
export interface EscalationStep {
account: string;
deadline: string;
}
/**
* The organisation settings. The server replaces all of them on save, so a page
* that edits some sends back the rest as it read them.
*/
export interface OrgSettings {
approval_deadline: string;
default_owner: string;
escalation: EscalationStep[];
[other: string]: unknown;
}
export interface Credential {
name: string;
kind: string;
+1 -1
View File
@@ -35,7 +35,7 @@ const orgSpecs: NavSpec[] = [
sections: [
{
label: "People & access",
paths: ["/org/members", "/org/approvals", "/org/agents", "/org/workspaces", "/org/policies", "/org/denials", "/org/audit"],
paths: ["/org/members", "/org/agents", "/org/workspaces", "/org/policies", "/org/denials", "/org/audit"],
},
{
label: "Agents",
-167
View File
@@ -1,167 +0,0 @@
<script setup lang="ts">
import { Plus, Trash2 } from "@lucide/vue";
import { computed, onMounted, ref } from "vue";
import { storeToRefs } from "pinia";
import PageHeader from "@/base/PageHeader.vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { DurationInput } from "@/components/ui/duration-input";
import { ReadError } from "@/components/ui/read-error";
import { Section } from "@/components/ui/section";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { SettingRow } from "@/components/ui/setting-row";
import { errors } from "@/copy/errors";
import { api, describeError, type OrgSettings } from "@/lib/api";
import { useOrgStore } from "@/stores/org";
import type { Member } from "./org";
// The select has no empty option value, so "no default owner" is this marker.
const NONE = "none";
// Default deadline for a new step. The server accepts one minute to 30 days.
const NEW_STEP_DEADLINE = "4h";
interface Draft {
approval_deadline: string;
default_owner: string;
escalation: { account: string; deadline: string }[];
}
const orgStore = useOrgStore();
const { org } = storeToRefs(orgStore);
const saved = ref<OrgSettings | null>(null);
const people = ref<Member[]>([]);
const draft = ref<Draft | null>(null);
const loadError = ref("");
const saveError = ref("");
const busy = ref(false);
// Only people with an org-wide membership can approve; the server rejects anyone else.
const eligible = computed(() => people.value.filter((member) => member.kind === "user" && !member.workspace_id));
const nameOf = (id: string) => eligible.value.find((member) => member.identity_id === id)?.display_name ?? id;
function toDraft(settings: OrgSettings): Draft {
return {
approval_deadline: settings.approval_deadline,
default_owner: settings.default_owner,
escalation: settings.escalation.map((step) => ({ ...step })),
};
}
const dirty = computed(() => saved.value !== null && JSON.stringify(draft.value) !== JSON.stringify(toDraft(saved.value)));
async function load(): Promise<void> {
loadError.value = "";
try {
await orgStore.loadOrg();
if (!org.value) return;
const [settings, members] = await Promise.all([api.orgSettings(), api.orgMembers<{ members: Member[] }>(org.value.id)]);
people.value = members.members;
saved.value = settings;
draft.value = toDraft(settings);
} catch (cause) {
loadError.value = describeError(cause, errors.common.unknown);
}
}
// A person can appear on the path only once, so each step offers its current
// selection plus the people not used by other steps.
function choices(account: string) {
const taken = new Set(draft.value?.escalation.map((step) => step.account));
return eligible.value.filter((member) => member.identity_id === account || !taken.has(member.identity_id));
}
const canAdd = computed(() => draft.value !== null && choices("").length > 0);
function addStep(): void {
const next = choices("")[0];
if (draft.value && next) draft.value.escalation.push({ account: next.identity_id, deadline: NEW_STEP_DEADLINE });
}
async function save(): Promise<void> {
if (!saved.value || !draft.value || busy.value) return;
busy.value = true;
saveError.value = "";
try {
const updated = await api.putOrgSettings({ ...saved.value, ...draft.value });
saved.value = updated;
draft.value = toDraft(updated);
} catch (cause) {
saveError.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
}
}
onMounted(load);
</script>
<template>
<div>
<PageHeader title="Approvals" />
<ReadError v-if="loadError" :message="loadError" retry-label="Retry" @retry="load" />
<form v-else-if="draft" @submit.prevent="save">
<Section>
<SettingRow label="Default owner" for="approvals-owner">
<Select
:model-value="draft.default_owner || NONE"
@update:model-value="draft.default_owner = $event === NONE ? '' : String($event)"
>
<SelectTrigger id="approvals-owner" class="w-64">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem :value="NONE">None</SelectItem>
<SelectItem v-for="member in eligible" :key="member.identity_id" :value="member.identity_id">
{{ member.display_name }}
</SelectItem>
</SelectContent>
</Select>
</SettingRow>
<SettingRow label="Approval deadline" for="approvals-deadline">
<DurationInput id="approvals-deadline" v-model="draft.approval_deadline" :units="['m', 'h']" />
</SettingRow>
</Section>
<Section title="Escalation path">
<template #action>
<Button type="button" variant="ghost" size="icon" aria-label="Add a step" :disabled="!canAdd" @click="addStep">
<Plus />
</Button>
</template>
<ol class="flex flex-col gap-2">
<li v-for="(step, index) in draft.escalation" :key="index" class="flex flex-wrap items-center gap-3">
<span class="w-6 text-label text-fg-muted">{{ index + 1 }}</span>
<Select v-model="step.account">
<SelectTrigger class="w-64" :aria-label="`Person for step ${index + 1}`">
<SelectValue>{{ nameOf(step.account) }}</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem v-for="member in choices(step.account)" :key="member.identity_id" :value="member.identity_id">
{{ member.display_name }}
</SelectItem>
</SelectContent>
</Select>
<DurationInput v-model="step.deadline" :units="['m', 'h']" />
<Button
type="button"
variant="ghost"
size="icon"
:aria-label="`Remove step ${index + 1}`"
@click="draft.escalation.splice(index, 1)"
>
<Trash2 />
</Button>
</li>
</ol>
</Section>
<Alert v-if="saveError" variant="destructive" class="mb-4"><AlertDescription>{{ saveError }}</AlertDescription></Alert>
<div class="flex justify-end gap-2">
<Button type="button" variant="ghost" :disabled="busy || !dirty" @click="draft = toDraft(saved!)">Discard</Button>
<Button type="submit" :disabled="busy || !dirty">Save</Button>
</div>
</form>
</div>
</template>
+17 -11
View File
@@ -6,7 +6,7 @@ import PageHeader from "@/base/PageHeader.vue";
import CreateAccount from "@/accounts/CreateAccount.vue";
import { Section } from "@/components/ui/section";
import { storeToRefs } from "pinia";
import { onMounted, ref } from "vue";
import { computed, onMounted, ref } from "vue";
import { Pause, Play, Plus, Trash2 } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
@@ -33,7 +33,7 @@ import {
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { useOrgStore } from "@/stores/org";
import { ROLE_LABELS, ROLES, type Candidate, type Member, type Role } from "./org";
import { ROLE_LABELS, ROLES, type Member, type Role } from "./org";
/**
* The org's members and the role each holds. A membership is org-wide, or
@@ -41,7 +41,6 @@ import { ROLE_LABELS, ROLES, type Candidate, type Member, type Role } from "./or
* a member touches exactly that membership.
*/
const members = ref<Member[]>([]);
const candidates = ref<Candidate[]>([]);
const error = ref("");
const loading = ref(true);
const busy = ref("");
@@ -58,14 +57,9 @@ const personRole = ref<Role>("viewer");
async function load(): Promise<void> {
if (!org.value) return;
try {
const id = org.value.id;
const [list, offered] = await Promise.all([
api.orgMembers<{ members: Member[] }>(id),
api.orgMemberCandidates<{ identities: Candidate[] }>(id),
]);
if (org.value?.id !== id) return;
members.value = list.members;
candidates.value = offered.identities;
members.value = (
await api.orgMembers<{ members: Member[] }>(org.value.id)
).members;
error.value = "";
} catch (cause) {
error.value = describeError(cause, errors.common.unknown);
@@ -75,6 +69,7 @@ async function load(): Promise<void> {
onMounted(async () => {
try {
await identities.loadOrg();
identities.watchIdentities();
await load();
} catch (cause) {
error.value = describeError(cause, errors.common.unknown);
@@ -83,6 +78,17 @@ onMounted(async () => {
}
});
// Active identities that hold no org-wide membership yet, so Add cannot pick
// someone the table already shows. The system identity is not a person.
const candidates = computed(() => {
const taken = new Set(
members.value.filter((m) => !m.workspace_id).map((m) => m.identity_id),
);
return identities.identities.filter(
(i) => i.kind !== "system" && i.lifecycle === "active" && !taken.has(i.id),
);
});
async function run(key: string, action: () => Promise<void>): Promise<void> {
busy.value = key;
try {
-7
View File
@@ -41,13 +41,6 @@ export const ROLE_LABELS: Record<Role, string> = {
viewer: "Viewer",
};
/** An identity that can be added to the org as a member. */
export interface Candidate {
id: string;
kind: string;
display_name: string;
}
export interface Member {
identity_id: string;
kind: string;
-7
View File
@@ -18,7 +18,6 @@ const OrgAccessPage = () => import("@/org/OrgAccessPage.vue");
const OrgUsagePage = () => import("@/org/OrgUsagePage.vue");
const SchedulingPolicyPage = () => import("@/settings/SchedulingPolicyPage.vue");
const ToolsPage = () => import("@/settings/ToolsPage.vue");
const OrgApprovalsPage = () => import("@/org/OrgApprovalsPage.vue");
const InstructionsPage = () => import("@/settings/InstructionsPage.vue");
const ExtensionsPage = () => import("@/settings/ExtensionsPage.vue");
const PluginsPage = () => import("@/settings/PluginsPage.vue");
@@ -326,12 +325,6 @@ export const routes: RouteRecordRaw[] = [
redirect: "/settings/models",
meta: { section: "org_config", label: "Models", navPath: "/org", description: "The organisation's agent models and aliases." },
},
{
path: "approvals",
name: "org-approvals",
component: OrgApprovalsPage,
meta: { section: "org_config", label: "Approvals", navPath: "/org", description: "Default owner, escalation path and approval deadline." },
},
{
path: "instructions",
name: "org-instructions",