carlos / platform Public

console: serviceBinding reads the bound account under the request

Astra round 1, P2: GET /api/cli/apps with a service credential resolved
its binding through serviceBinding, which read the account with the
context-free AccountByID wrapper, so a service-token request whose
client had gone stayed queued on the store's one connection.

serviceBinding now takes the request's context and reads through
AccountByIDContext. Its three callers all have a request and pass
r.Context(): handleAPIApps, apiPrincipalAccountSaying and teamInScope.
The refusals are unchanged; a failed read, a cancelled one included,
is the same refusal any store error was.

requestctx_test.go gains the service credential at /api/cli/apps in
both tests, and a case that holds the connection only once the request
reaches the binding's account read (pauseDB), past its bearer lookup.
On the previous tip the binding case kept its place behind the held
connection and the context check reported the context-free read; both
pass now. The db-no-context count is unchanged (897): the call site was
the wrapper, not the database, so the record has nothing to lower.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 9b8bd6be73c9fde8688cc4c40fa5db37a3ce5067 parent b663ba9
3 files changed, +91 −23
  • internal/console/apicli.go +7 −4
  • internal/console/requestctx_test.go +83 −18
  • internal/console/teamdoors.go +1 −1

CI cancelled — superseded by a newer push — run details

diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index f42fcbb1a..1c5398f8a 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -154,14 +154,17 @@ func auditActor(p Principal, acct *Account) string {
// Only a SERVICE principal has a binding here. A link principal is bound to
// an account too, but to the link doors alone: it is refused here by kind,
// so no service door can ever read it as a binding.
-func (s *Server) serviceBinding(p Principal) (*Account, bool) {
+//
+// The account read runs under ctx, the request's: a store error, a
+// cancelled request among them, is a refusal like any other.
+func (s *Server) serviceBinding(ctx context.Context, p Principal) (*Account, bool) {
if p.Kind != PrincipalService {
return nil, false
}
if p.AccountID == 0 || (p.Name == "" && p.App == "") {
return nil, false
}
- acct, err := s.store.AccountByID(p.AccountID)
+ acct, err := s.store.AccountByIDContext(ctx, p.AccountID)
if err != nil {
log.Printf("console: api principal account %d: %v", p.AccountID, err)
return nil, false
@@ -266,7 +269,7 @@ func (s *Server) apiPrincipalAccountSaying(w http.ResponseWriter, r *http.Reques
var addr string
switch p.Kind {
case PrincipalService:
- acct, ok := s.serviceBinding(p)
+ acct, ok := s.serviceBinding(r.Context(), p)
if !ok || seg != acct.Sqid {
http.NotFound(w, r)
return Principal{}, nil, false
@@ -762,7 +765,7 @@ func (s *Server) handleAPIApps(w http.ResponseWriter, r *http.Request) {
// an error — the credential's scope is simply empty — and above all
// it is not a fall-through to every account, which is the failure
// mode serviceBinding exists to refuse.
- if acct, ok := s.serviceBinding(p); ok {
+ if acct, ok := s.serviceBinding(r.Context(), p); ok {
accts = []Account{*acct}
}
case PrincipalUser:
diff --git a/internal/console/requestctx_test.go b/internal/console/requestctx_test.go
index 5cd344a37..912c93ede 100644
--- a/internal/console/requestctx_test.go
+++ b/internal/console/requestctx_test.go
@@ -10,6 +10,8 @@ import (
"sync"
"testing"
"time"
+
+ "github.com/carlosframework/platform/internal/svcrole"
)
// TestCancelledRequestLeavesTheConnectionQueue: the console store has one
@@ -20,9 +22,13 @@ import (
// return while the connection is still held, without the page's queries
// running.
//
+// A case with pauseAt is held up further in: the connection is taken only
+// once the request reaches that query (pauseDB), so the request is past
+// its bearer lookup and queued at the later one when the client goes.
+//
// The wait is on the pool's own counter (the request is queued once
-// WaitCount moves) and on the handler returning; the timer only bounds a
-// failure.
+// WaitCount moves), on pauseDB's signal and on the handler returning; the
+// timer only bounds a failure.
func TestCancelledRequestLeavesTheConnectionQueue(t *testing.T) {
fx := newConsoleFixture(t)
const person = "paul@keymail.dev"
@@ -31,16 +37,22 @@ func TestCancelledRequestLeavesTheConnectionQueue(t *testing.T) {
t.Fatal(err)
}
token := mintHostClaimToken(t, fx.st, person)
+ service := serviceToken(t, fx.st, OpsAccountID, "ci", "kass", svcrole.Publish)
cookie := func(r *http.Request) { r.AddCookie(&http.Cookie{Name: sessionCookie, Value: session}) }
bearer := func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+token) }
+ serviceBearer := func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+service) }
for _, c := range []struct {
name, path string
auth func(*http.Request)
+ pauseAt string
}{
- {"app list", fx.path("/"), cookie},
- {"app page", fx.path("/apps/kass"), cookie},
- {"instances", fx.path("/apps/kass/instances"), cookie},
- {"cli door", "/api/cli/apps", bearer},
+ {"app list", fx.path("/"), cookie, ""},
+ {"app page", fx.path("/apps/kass"), cookie, ""},
+ {"instances", fx.path("/apps/kass/instances"), cookie, ""},
+ {"cli door", "/api/cli/apps", bearer, ""},
+ {"cli door, service credential", "/api/cli/apps", serviceBearer, ""},
+ // serviceBinding's account read, after the bearer resolved.
+ {"cli door, service binding", "/api/cli/apps", serviceBearer, "FROM accounts WHERE id = ?"},
} {
t.Run(c.name, func(t *testing.T) {
// The door answers this caller when nothing is in its way.
@@ -48,22 +60,33 @@ func TestCancelledRequestLeavesTheConnectionQueue(t *testing.T) {
c.auth(req)
rec := httptest.NewRecorder()
fx.srv.ServeHTTP(rec, req)
- if rec.Code != http.StatusOK {
- t.Fatalf("GET %s = %d with the connection free, want 200:\n%s", c.path, rec.Code, rec.Body)
+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "kass") {
+ t.Fatalf("GET %s = %d with the connection free, want 200 naming kass:\n%s", c.path, rec.Code, rec.Body)
}
- held, err := fx.st.rawPool.Conn(context.Background())
- if err != nil {
- t.Fatal(err)
- }
+ var held *sql.Conn
released := false
release := func() {
- if !released {
+ if held != nil && !released {
released = true
held.Close()
}
}
defer release()
+ hold := func() {
+ var err error
+ if held, err = fx.st.rawPool.Conn(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var pause *pauseDB
+ if c.pauseAt != "" {
+ pause = &pauseDB{sqlHandle: fx.st.db, at: c.pauseAt, reached: make(chan struct{}), proceed: make(chan struct{})}
+ fx.st.db = pause
+ defer func() { fx.st.db = pause.sqlHandle }()
+ } else {
+ hold()
+ }
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -77,6 +100,18 @@ func TestCancelledRequestLeavesTheConnectionQueue(t *testing.T) {
fx.srv.ServeHTTP(rec, req)
}()
bound := time.After(10 * time.Second)
+ if pause != nil {
+ select {
+ case <-pause.reached:
+ case <-done:
+ t.Fatalf("GET %s returned %d before it reached %q", c.path, rec.Code, c.pauseAt)
+ case <-bound:
+ t.Fatalf("GET %s never reached %q", c.path, c.pauseAt)
+ }
+ hold()
+ waits = fx.st.rawPool.Stats().WaitCount
+ close(pause.proceed)
+ }
for fx.st.rawPool.Stats().WaitCount == waits {
select {
case <-done:
@@ -98,11 +133,11 @@ func TestCancelledRequestLeavesTheConnectionQueue(t *testing.T) {
if released {
t.Fatal("the held connection was let go before the request returned")
}
- // It gave up at the first query, the session or bearer
- // lookup: the caller reads as signed out, and nothing of the
- // page was served.
- if rec.Code == http.StatusOK {
- t.Fatalf("GET %s = 200 after the client went away, want the signed-out answer", c.path)
+ // It gave up at the query it was queued at: the session or
+ // bearer lookup reads as signed out, the service binding as no
+ // binding, and nothing of the page was served.
+ if rec.Code == http.StatusOK && strings.Contains(rec.Body.String(), "kass") {
+ t.Fatalf("GET %s served the page after the client went away:\n%s", c.path, rec.Body)
}
})
}
@@ -123,6 +158,7 @@ func TestSignedInPagesQueryUnderTheRequestContext(t *testing.T) {
t.Fatal(err)
}
token := mintHostClaimToken(t, fx.st, person)
+ service := serviceToken(t, fx.st, OpsAccountID, "ci", "kass", svcrole.Publish)
check := &requestCtxDB{sqlHandle: fx.st.db}
fx.st.db = check
t.Cleanup(func() { fx.st.db = check.sqlHandle })
@@ -134,6 +170,7 @@ func TestSignedInPagesQueryUnderTheRequestContext(t *testing.T) {
{"app page", fx.path("/apps/kass"), session},
{"instances", fx.path("/apps/kass/instances"), session},
{"cli door", "/api/cli/apps", "Bearer " + token},
+ {"cli door, service credential", "/api/cli/apps", "Bearer " + service},
} {
t.Run(c.name, func(t *testing.T) {
ctx := context.WithValue(context.Background(), requestCtxMark{}, c.path)
@@ -249,3 +286,31 @@ func (d *requestCtxDB) PrepareContext(ctx context.Context, query string) (*sql.S
d.note(ctx, "PrepareContext", query)
return d.sqlHandle.PrepareContext(ctx, query)
}
+
+// pauseDB holds up the first query containing at: it says so on reached
+// and goes on to the store only once proceed is closed.
+type pauseDB struct {
+ sqlHandle
+ at string
+ once sync.Once
+ reached, proceed chan struct{}
+}
+
+func (d *pauseDB) wait(query string) {
+ if strings.Contains(query, d.at) {
+ d.once.Do(func() {
+ close(d.reached)
+ <-d.proceed
+ })
+ }
+}
+
+func (d *pauseDB) QueryRow(query string, args ...any) *sql.Row {
+ d.wait(query)
+ return d.sqlHandle.QueryRow(query, args...)
+}
+
+func (d *pauseDB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row {
+ d.wait(query)
+ return d.sqlHandle.QueryRowContext(ctx, query, args...)
+}
diff --git a/internal/console/teamdoors.go b/internal/console/teamdoors.go
index 45983a6ab..b991fe8c6 100644
--- a/internal/console/teamdoors.go
+++ b/internal/console/teamdoors.go
@@ -288,7 +288,7 @@ func (tv *teamView) claimInScope(ctx context.Context, s *Server, c *domains.Clai
// as either in or out of scope; a console with no bucket answers the
// instance family's 503 before any read.
func (s *Server) teamInScope(w http.ResponseWriter, r *http.Request, p Principal, target scopeTarget) (*teamView, bool) {
- acct, ok := s.serviceBinding(p)
+ acct, ok := s.serviceBinding(r.Context(), p)
if !ok || r.PathValue("account") != acct.Sqid || p.App == "" || p.App != r.PathValue("app") {
http.NotFound(w, r)
return nil, false