Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,10 @@ A folder whose `agent.yaml` names a `plugins` list now fails to load with `plugi

`Folder.load`, and so `Agent.new(folder: "…")`, raise a `ConfigurationError` for a folder whose agent.yaml names `plugins:`, with an error that names the file and points to `connectors:`. An empty or null `plugins` still loads and sends nothing, as before. Folder sync no longer sends `plugins`, and the warning that plugins are deprecated is gone, as is the check that no name is under both `connectors` and `plugins`. Move each plugin to a `connectors:` entry (AI-2528).

### `POST /v1/phone/opt-outs` refuses a recipient it could never match

A `recipient` that is neither an E.164 number nor, for channel `imessage` or `all`, an iMessage handle's email address is now refused with a 400 `validation_failed` instead of being stored. Such opt-outs never took effect: an opt-out is matched against the number or handle as written, and numbers are always E.164. `15551110000` and `(555) 111-0000` are refused; send `+15551110000`.

## Bug Fixes

### A scheduled task whose turn is refused for money in an open conversation fails its run
Expand Down
6 changes: 3 additions & 3 deletions acceleration/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4286,8 +4286,8 @@ components:
channel:
$ref: '#/components/schemas/OptOutChannel'
recipient:
description: The number, in E.164.
maxLength: 20
description: The number in E.164, or an iMessage handle's email address, for channel imessage or all.
maxLength: 254
minLength: 2
type: string
source:
Expand Down Expand Up @@ -7071,7 +7071,7 @@ components:
id:
type: string
recipient:
description: The number, in E.164.
description: The number in E.164, or an iMessage handle's email address.
type: string
source:
description: keyword when they texted STOP, campaign when they asked a campaign call not to call again, otherwise api or dashboard.
Expand Down
29 changes: 27 additions & 2 deletions acceleration/internal/api/dlc.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"io"
"net/http"
"net/mail"
"slices"
"strings"
"time"
Expand Down Expand Up @@ -248,6 +249,9 @@ func (s *Server) createOptOut(ctx context.Context, request *createOptOutRequest)
Channel: string(request.Body.Channel),
Source: "api",
}
if err := optOutRecipient(optOut.Recipient, optOut.Channel); err != nil {
return nil, err
}
if request.Body.Source != nil {
optOut.Source = *request.Body.Source
}
Expand All @@ -257,6 +261,27 @@ func (s *Server) createOptOut(ctx context.Context, request *createOptOutRequest)
return &optOutResponse{Body: renderedOptOut(optOut)}, nil
}

// errOptOutRecipient is a recipient an opt-out would never match: one is matched against the
// recipient of a text or call as it is written, a number in E.164 or, on iMessage, the email
// address of a handle (the Linq bridge writes such a STOP).
var errOptOutRecipient = APIError{Type: ErrorTypeInvalidRequest, Code: codeValidationFailed,
Message: "recipient must be a number in E.164, such as +15550001111, or for channel imessage or all an email address"}

// optOutRecipient refuses a recipient channel could never be reached at.
func optOutRecipient(recipient, channel string) error {
if store.IsE164(recipient) {
return nil
}
if channel != dlc.IMessage && channel != store.OptOutAll {
return errOptOutRecipient
}
address, err := mail.ParseAddress(recipient)
if err != nil || address.Address != recipient {
return errOptOutRecipient
}
return nil
}

func (s *Server) revokeOptOut(ctx context.Context, request *revokeOptOutRequest) (*struct{}, error) {
customerID, err := s.dlcCustomer(ctx)
if err != nil {
Expand Down Expand Up @@ -792,7 +817,7 @@ func (OptOutChannel) Schema(registry huma.Registry) *huma.Schema {
// OptOut is somebody who asked not to be reached.
type OptOut struct {
Id string `json:"id"`
Recipient string `json:"recipient" doc:"The number, in E.164."`
Recipient string `json:"recipient" doc:"The number in E.164, or an iMessage handle's email address."`
Channel OptOutChannel `json:"channel"`
Source string `json:"source" doc:"keyword when they texted STOP, campaign when they asked a campaign call not to call again, otherwise api or dashboard."`
CreatedAt time.Time `json:"created_at"`
Expand All @@ -813,7 +838,7 @@ type OptOutPage struct {

// CreateOptOutRequest records an opt-out the app heard about another way.
type CreateOptOutRequest struct {
Recipient string `json:"recipient" minLength:"2" maxLength:"20" doc:"The number, in E.164."`
Recipient string `json:"recipient" minLength:"2" maxLength:"254" doc:"The number in E.164, or an iMessage handle's email address, for channel imessage or all."`
Channel OptOutChannel `json:"channel"`
Source *string `json:"source,omitempty" enum:"api,dashboard" doc:"Omitted is api."`
}
Expand Down
25 changes: 25 additions & 0 deletions acceleration/internal/api/dlc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -921,6 +921,31 @@ func (s *DLCSuite) TestAUseCaseIsHiddenFromOtherApps() {
})
}

func (s *DLCSuite) TestAnOptOutNotInE164IsRefused() {
for _, recipient := range []string{"15551110000", "+1 555 111 0000", "(555) 111-0000", "+0155511100",
"+15551110000x", "+1555111000012345", "ada@example.com"} {
status, body := s.serverClient.call(http.MethodPost, "/v1/phone/opt-outs",
CreateOptOutRequest{Recipient: recipient, Channel: OptOutChannel(dlc.SMS)})
s.Equal(http.StatusBadRequest, status, "%q would never match a text sent", recipient)
s.Contains(string(body), `"code":"validation_failed"`, recipient)
}
s.Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/phone/opt-outs",
CreateOptOutRequest{Recipient: "+15551110000", Channel: OptOutChannel(dlc.Voice)}, nil))
}

func (s *DLCSuite) TestAnIMessageHandlesAddressIsAnOptOutOnIMessageOnly() {
for _, channel := range []string{dlc.IMessage, store.OptOutAll} {
s.Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/phone/opt-outs",
CreateOptOutRequest{Recipient: "ada@example.com", Channel: OptOutChannel(channel)}, nil), channel)
}
for _, recipient := range []string{"Ada <ada@example.com>", "ada", "15551110000"} {
status, body := s.serverClient.call(http.MethodPost, "/v1/phone/opt-outs",
CreateOptOutRequest{Recipient: recipient, Channel: OptOutChannel(dlc.IMessage)})
s.Equal(http.StatusBadRequest, status, recipient)
s.Contains(string(body), `"code":"validation_failed"`, recipient)
}
}

func (s *DLCSuite) TestADialToSomebodyWhoOptedOutIsRefused() {
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPut, "/v1/phone/sandbox/recipients",
SetSandboxRecipientsRequest{Recipients: []string{"+15551110000"}}, nil))
Expand Down
80 changes: 80 additions & 0 deletions acceleration/internal/api/requestid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,86 @@ func TestACredentialTheKeyStoreCouldNotCheckIsAnsweredAsInternalNotAsAWrongKey(t
require.Equal(t, http.StatusUnauthorized, ask().Code, "a key the store refused is still the caller's to fix")
}

func TestACallerThatHangsUpWhileItsKeyIsCheckedIsNoFailure(t *testing.T) {
broken, err := store.Open("postgres://router_app:hunter2@127.0.0.1:1/agents_prod?sslmode=disable")
require.NoError(t, err)
t.Cleanup(func() { _ = broken.Close() })
lookup := broken.APIKeys.Lookup(nil)
key, _, err := auth.NewCredential(auth.Live)
require.NoError(t, err)
logged := &bytes.Buffer{}
server, err := NewServer(Options{
Routers: map[routing.Modality]routing.Inspector{routing.LLM: idleInspector{}},
AuthMode: auth.Custom,
Auth: auth.Func(func(ctx context.Context, _ *http.Request) (auth.Principal, error) {
_, err := lookup(ctx, key)
return auth.Principal{}, err
}),
Logger: slog.New(slog.NewTextHandler(logged, nil)),
})
require.NoError(t, err)
ctx, hangUp := context.WithCancel(context.Background())
hangUp()
response := httptest.NewRecorder()
gone := map[string]string{"route": "/v1/agents/configs", "status": "4xx"}
answered := map[string]string{"route": "/v1/agents/configs", "status": "2xx"}
goneBefore, answeredBefore := sumOf(t, "router_http_requests_total", gone), sumOf(t, "router_http_requests_total", answered)

server.Handler().ServeHTTP(response, httptest.NewRequestWithContext(ctx, http.MethodGet, "/v1/agents/configs", nil))

require.Equal(t, statusClientClosed, response.Code, response.Body.String())
require.NotContains(t, logged.String(), "level=ERROR", "a caller hanging up is not an outage")
require.Equal(t, goneBefore+1, sumOf(t, "router_http_requests_total", gone), "a caller that gave up is counted")
require.Equal(t, answeredBefore, sumOf(t, "router_http_requests_total", answered), "nor as an answer")
}

func TestAKeyStoreDownIsAFailureEvenIfTheCallerHasGone(t *testing.T) {
broken, err := store.Open("postgres://router_app:hunter2@127.0.0.1:1/agents_prod?sslmode=disable")
require.NoError(t, err)
t.Cleanup(func() { _ = broken.Close() })
lookup := broken.APIKeys.Lookup(nil)
key, _, err := auth.NewCredential(auth.Live)
require.NoError(t, err)
logged := &bytes.Buffer{}
server, err := NewServer(Options{
Routers: map[routing.Modality]routing.Inspector{routing.LLM: idleInspector{}},
AuthMode: auth.Custom,
// The lookup fails on its own, as an unreachable store does, not for the caller leaving.
Auth: auth.Func(func(context.Context, *http.Request) (auth.Principal, error) {
_, err := lookup(context.Background(), key)
return auth.Principal{}, err
}),
Logger: slog.New(slog.NewTextHandler(logged, nil)),
})
require.NoError(t, err)
ctx, hangUp := context.WithCancel(context.Background())
hangUp()

server.Handler().ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(ctx, http.MethodGet, "/v1/agents/configs", nil))

require.Contains(t, logged.String(), "level=ERROR", "an outage is logged whoever is left to hear of it")
require.Contains(t, logged.String(), "127.0.0.1:1")
}

func TestALookupCancelledWhileTheCallerWaitsIsStillAFailure(t *testing.T) {
logged := &bytes.Buffer{}
server, err := NewServer(Options{
Routers: map[routing.Modality]routing.Inspector{routing.LLM: idleInspector{}},
AuthMode: auth.Custom,
Auth: auth.Func(func(context.Context, *http.Request) (auth.Principal, error) {
return auth.Principal{}, stack.Wrap(fmt.Errorf("store: get api key: %w", context.Canceled))
}),
Logger: slog.New(slog.NewTextHandler(logged, nil)),
})
require.NoError(t, err)
response := httptest.NewRecorder()

server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/v1/agents/configs", nil))

require.Equal(t, http.StatusInternalServerError, response.Code, "the caller is still there to be told")
require.Contains(t, logged.String(), "level=ERROR")
}

func TestAServerErrorNeverWrappedIsLoggedWithTheStackItReachedHumaOn(t *testing.T) {
handler, logged := served(t, func() error { return errors.New("never wrapped") })

Expand Down
13 changes: 13 additions & 0 deletions acceleration/internal/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -1345,6 +1345,10 @@ var errServerSideOnly = APIError{
// is how a backend says which of its users it is opening a session for, so that the user's
// own device can reach that session afterwards; what keeps the limit off it is that
// withQuota looks at whether the caller is server-side rather than at whether there is one.
// statusClientClosed is what a request whose caller hung up before it was answered is counted
// as, nginx's 499: no caller reads it.
const statusClientClosed = 499

func (s *Server) withCustomer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Stream is not a customer, and a delivery is authenticated by its signature. Who a
Expand Down Expand Up @@ -1374,6 +1378,15 @@ func (s *Server) withCustomer(next http.Handler) http.Handler {
Message: strings.TrimPrefix(err.Error(), "auth: ")})
return
}
// A caller that hung up while its credential was checked is no failure of the router's,
// and nobody is left to answer. The status is for withMetrics, which counts and times it
// as a 4xx: callers giving up on a stalled key store still show there.
if errors.Is(err, context.Canceled) && r.Context().Err() != nil {
s.logger.Debug("the caller left before its credential was checked", "method", r.Method,
"path", loggedPath(s.mux, r), "request_id", RequestIDFrom(r.Context()))
w.WriteHeader(statusClientClosed)
return
}
// A credential that could not be checked (the key store down, a key that would not
// unseal) is the router's failure, not a wrong key. It is logged here: withRequestLog
// runs after this.
Expand Down
36 changes: 33 additions & 3 deletions acceleration/internal/session/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -1051,9 +1051,11 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er
m.records.Closed(spec.CustomerID, created.id, row.OpenedAt, time.Now().UTC(), created.kept())
})
if spec.Reopened.IsZero() {
m.records.Opened(row, toolRows(created))
m.records.Opened(row, toolRows(created), func() { m.idTaken(created) })
} else {
m.records.CarriedOn(row, toolRows(created))
// A carry-on skips the check that the id is free, so another customer's row written
// on another shard meanwhile refuses it too.
m.records.CarriedOn(row, toolRows(created), func() { m.idTaken(created) })
}
created.startRecording()
}
Expand All @@ -1075,7 +1077,8 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er
m.calls.Ended(spec.CustomerID, id, time.Now().UTC())
// The review runs on a model rather than in this closer, so it is started
// here and lands on the row whenever it comes back.
if !spec.NoReview {
// A session whose row the store refused (idTaken) has no call row to land on.
if !spec.NoReview && !created.idTaken.Load() {
m.reviews.Review(row(created), spec.Attribution, spec.Region, spec.reviewTarget(), spec.ReviewInstructions, created.conversation())
}
})
Expand All @@ -1099,6 +1102,13 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er
fail()
return nil, stack.Wrap(ErrSessionExists)
}
// Its row was refused before the session was held, so idTaken found nothing to end.
if created.idTaken.Load() {
m.mu.Unlock()
turnedAway = true
fail()
return nil, stack.Wrap(ErrSessionExists)
}
m.sessions[created.Key()] = created
sessionsActive.Inc()
created.active.Store(true)
Expand Down Expand Up @@ -1726,6 +1736,26 @@ func (m *Manager) end(found *Session, reason EndReason) {
found.abandon()
}

// idTaken ends created, whose row the store refused because another customer's session has its
// id: the check that an id is free (Create) runs before the row is written, so two routers
// opening one id for two customers both pass it. One not held yet is turned away by Create.
// It runs on the record writer, so the close, which may wait on the writer, runs beside it.
func (m *Manager) idTaken(created *Session) {
created.idTaken.Store(true)
m.logger.Warn("ending a session whose id another customer's session has",
"session", created.id, "customer", created.Spec().CustomerID)
done, held := m.take(created)
if !held {
return
}
created.noteEnd(EndClosed)
go func() {
defer done()
m.release(created)
Comment thread
thesyncim marked this conversation as resolved.
Resolved
created.abandon()
}()
}

// hangUp ends found for its agent hanging up, or reason. It closes as Close does, so the
// goodbye is not cut short, and in the background: the agent hangs up from inside its own
// tool call, and closing the session waits for the agent.
Expand Down
Loading
Loading