diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c419b6..1dac175 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,26 @@ Notable changes to this service, newest first, per release. This file is written for whoever runs the service or integrates against it. +## v0.12.0 + +### Added + +- **An AI app's connection is named, listed and signed out.** When the app redeems its code the connection gets a + public name, its time of connecting and a place in its assistant's index; its app tokens state the name as `sid`. + `GET /identity/connections` lists the apps connected as the caller's own assistants in their workspace, and + `DELETE /identity/connections/{id}` signs one out; `GET`, `DELETE /identity/assistants/{assistant}/connections[/{id}]` + do the same for an administrator of the workspace (`membership:admin`), any person's, and end them all. Each takes a + person's own token only. A sign-out is recorded as a security event (`connection_signed_out`) naming who did it. + +### Changed + +- **An AI app's token stops at once when its connection ends.** Its exchange is refused, `401 err:connection:ended`, + unless the connection its `sid` names is live and still its person's, app's and assistant's, though the token has + not expired; a live one is marked used, at most once a minute. An app token minted before this version names no + connection and is refused at its next exchange, so an app connected before it signs in again. An exchanging + client that keeps passes made from app tokens should ask for one at every call (go-authbyte's + `ExchangeDelegatedToken`), or a kept pass outlives the sign-out. + ## v0.11.0 ### Changed diff --git a/README.md b/README.md index 45116e3..80c24fc 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,11 @@ Endpoints are registered in [`routes/router.go`](routes/router.go). The two opti | `GET /identity` | The internal identity plus `loa`, `login_method` and, to a token of a client whose row says `signing: true`, the signing flows that method permits. A token for any enabled sign-in client's audience is accepted | valid user token (DPoP) | | `POST /identity/persons` | Register a person before their first login: the identity code (any spelling; stored canonical) and the name create the person row with a stable subject and **no credential** — the subject an administrator then invites them to a membership register under. Idempotent on the code: `201` created, `200` already known (names filled only where the row has none); a code naming no country or an unknown identity type is `422 err:identity:invalid` (never echoed) | valid token carrying `identity:admin` (DPoP) | | `POST /identity/persons/lines` | Read, for up to 500 people at once (`{"subjects": ["sub:", …]}`), whether each can sign in and what is known about how: the email a directory sign-in left (only when one is kept) and, for a person holding a national identity code, its country and displayed length — **never the code**. A person the platform does not know is left out. More than 500, an empty or non-list body or a malformed subject is `422 err:identity:invalid` (the values sent are never repeated). Answered `Cache-Control: no-store` | a **service acting as itself** (its own token: subject `svc:…`, naming no organisation and no actor) carrying `identity:lines` — a person's token, a token exchanged to act for someone and a service account's token for an organisation never read it, even holding the scope (DPoP) | +| `GET /identity/connections` | The AI apps connected as the caller's own assistants in the workspace their token names: `{"assistants": [{"key", "name", "connections": [{"id", "app", "connectedAt", "lastUsed"}]}]}`, an assistant with none listed with none, newest connection first, `lastUsed` `null` until a call went through. `502 err:upstream:unavailable` when the register cannot answer which assistants are theirs; `no-store` | a **person's own token** naming a workspace (no actor, not an AI app's, not a service's): otherwise `403 err:connection:forbidden` (DPoP) | +| `DELETE /identity/connections/{id}` | Sign out one of the caller's own connected apps by its public name: its session and refresh token end, its app's next exchange is refused at once, the person's others go on; recorded as a security event naming the doer. `204`; `404 err:connection:not_found` for a name that is not theirs, or not live | as above | +| `GET /identity/assistants/{assistant}/connections` | The AI apps connected as one assistant of the workspace the token names, any person's: `{"connections": [{"id", "app", "connectedAt", "lastUsed"}]}`. Another workspace's assistant reads as having none; a key not shaped `svc:assistant-` is `404` | a person's own token holding the register's administering level, `membership:admin`; otherwise `403` (DPoP) | +| `DELETE /identity/assistants/{assistant}/connections/{id}` | Sign out one app connected as the assistant, as the person's own sign-out does, the administrator recorded as the doer. `204`; `404` when it is not that assistant's live connection in this workspace | as above | +| `DELETE /identity/assistants/{assistant}/connections` | Sign out every app connected as the assistant, at once (what its removal asks first). `204`, with none to end as well | as above | | `GET /identity/persons/{personSub}/code` | Read one person's national identity code the way a person is shown it, with its country: `{"code": "…", "country": "LV"}`. A person not known, or holding no code, is `404 err:identity:not_found`; a malformed id is `422 err:identity:invalid`. Each code answered is recorded with the access audit as a routine read of the person by the calling service (`identity.read`, marked `identityCode`, never the code); the caller records the disclosure it makes onward. Answered `Cache-Control: no-store` | a **service acting as itself** carrying `identity:code`, refused as the lines read refuses — a grant for `identity:lines` never reaches a code (DPoP) | | `POST /authorize/card` | The sign-in page's card answer: the card signed the challenge the page was shown with. Its address carries the client's request, checked again; it needs the browser's binding cookie, the page's token, an `Origin` equal to `BASE_URL`'s and a challenge that browser was given; the engine checks the token, and the browser goes back to the client with a code (303), or to the page | anonymous (the page's browser) — **only if `WEBEID_ENGINE_URL` set** | | `GET /.well-known/jwks.json` | Signing public keys (active + retired-within-window) | anonymous | @@ -391,7 +396,14 @@ answers a new one, and one used again ends that connection. **Every refresh asks the assistant removed or given to another person, or the person gone from the workspace, ends the connection; a box the assistant lost is gone from the next token. A connection is a session of its own, not the browser's shared one, lasting at most `SESSION_TTL`; the app ends it at `/revoke` with its -refresh token and no key, which ends nothing else. **A token exchanged from an AI app's token** (its +refresh token and no key, which ends nothing else. **A connection is named and listed:** when the app redeems its +code the connection gets a public name of its own (never its session's key or a token), its time of connecting, and a +place in its assistant's index (per workspace and assistant, until the connection's end); each app token states that +name as its `sid`. **It stops at once when it ends:** an exchange of an AI app's token is refused, `401 +err:connection:ended`, unless the connection its `sid` names is live, still the token's person's, app's and +assistant's, though the token itself has not expired; a live one is marked used, at most once a minute. A person +lists the apps connected as their own assistants and signs one out; a workspace's administrator does the same for an +assistant's, and ends them all when it is removed (the `/identity/connections` routes, above). **A token exchanged from an AI app's token** (its `login_method` is `assistant`) carries no box (`service/feature:act`) the app token lacks, at every hop, whatever the exchanging client's grant allows. A level (`group:level`) of the exchanging client's own grant passes only where its grant toward that audience names it under `assistant_levels`, so a service can still do its own work for the person, diff --git a/app.go b/app.go index 585a9e0..dca33a1 100644 --- a/app.go +++ b/app.go @@ -164,6 +164,12 @@ type SessionStore interface { LoadShared(ctx context.Context, id string) (*session.Shared, error) PutSharedApp(ctx context.Context, id, client, sid string, until time.Time) (string, error) EndShared(ctx context.Context, id string) (map[string]string, error) + // AddConnection keeps an AI app's connection in its assistant's index, by + // workspace and assistant, until until; Connections answers the index's live + // ones; RemoveConnection takes one out, and is no error when it is gone. + AddConnection(ctx context.Context, tenant, assistant string, c session.Connection, until time.Time) error + Connections(ctx context.Context, tenant, assistant string) ([]session.Connection, error) + RemoveConnection(ctx context.Context, tenant, assistant string, c session.Connection) error Ping(ctx context.Context) error } diff --git a/audit/audit.go b/audit/audit.go index c0f3a91..3a0d5b3 100644 --- a/audit/audit.go +++ b/audit/audit.go @@ -87,6 +87,21 @@ func (r *Recorder) SessionEnded(ctx *azugo.Context, actorID, method string) { actorRef(actorID, "user", ""), attrs) } +// ConnectionSignedOut records an AI app's connection signed out by a person, its +// own, or by an administrator of its workspace: actorID did it, personID's app +// (clientID) stopped. +func (r *Recorder) ConnectionSignedOut(ctx *azugo.Context, actorID, personID, clientID string, byAdministrator bool) { + by := "person" + if byAdministrator { + by = "administrator" + } + + r.emit(ctx, secevents.EventAuthentication, secevents.SeverityInfo, broker.OutcomeSuccess, + actorRef(actorID, "user", ""), map[string]any{ + secevents.AttrKind: "connection_signed_out", "person": personID, "client": clientID, "by": by, + }) +} + // Logout records the browser's leg of a sign-out. It names no person: the // session is ended server to server (SessionEnded), and the browser's address // carries no value that names it. Federated indicates the browser was sent on to diff --git a/issuer/delegated_test.go b/issuer/delegated_test.go index 01edab2..0feee44 100644 --- a/issuer/delegated_test.go +++ b/issuer/delegated_test.go @@ -46,7 +46,7 @@ func TestIssueDelegatedActsForUser(t *testing.T) { t.Fatalf("IssueUser: %v", err) } - subject, err := iss.ParseSubjectToken(userTok) + subject, _, err := iss.ParseSubjectToken(userTok) if err != nil { t.Fatalf("ParseSubjectToken: %v", err) } @@ -144,7 +144,7 @@ func TestExchangeActorChainNests(t *testing.T) { func TestParseSubjectTokenRejectsGarbage(t *testing.T) { iss, _, _ := newStack(t) - if _, err := iss.ParseSubjectToken("not-a-jwt"); err == nil { + if _, _, err := iss.ParseSubjectToken("not-a-jwt"); err == nil { t.Fatal("expected ParseSubjectToken to reject a non-token") } } diff --git a/issuer/issuer.go b/issuer/issuer.go index fe04c58..6c7adee 100644 --- a/issuer/issuer.go +++ b/issuer/issuer.go @@ -112,28 +112,48 @@ type AppTokenInput struct { Assistant string // the assistant's key, svc:assistant- LoA string // always the lowest: the app holds no sign-in of its own LoginMethod string // always identity.LoginAssistant - TTL time.Duration + // Connection is the connection's public name, stated as the token's sid, so + // an exchange can tell whether the connection the token was made for is + // still live; "" names none, and such a token is exchanged for nothing. + Connection string + TTL time.Duration +} + +// appClaims are an AI app's token's claims: an access token's, and the +// connection it was made for [OIDC Front-Channel Logout 1.0 §3, the sid claim]. +type appClaims struct { + claims.Claims + + SID string `json:"sid,omitempty"` } // IssueApp mints an AI app's token: a plain bearer token, with no cnf, since an // AI app holds no proof-of-possession key [MCP 2026-07-28 basic/authorization]; // the one kind of token this issuer mints unbound, kept to its one resource by -// its audience and to minutes by its lifetime. +// its audience, to minutes by its lifetime, and to its connection by its sid. func (i *Issuer) IssueApp(in AppTokenInput) (string, int64, error) { if in.Assistant == "" || in.TTL <= 0 { return "", 0, fmt.Errorf("issuer: an app token names its assistant and its lifetime") } - c := claims.Claims{ - RegisteredClaims: i.base(in.Subject, in.Audience, in.TTL), - Scope: strings.Join(in.Scopes, " "), - LoA: in.LoA, - LoginMethod: in.LoginMethod, - Tenant: in.Tenant, - ClientID: in.ClientID, - Act: &claims.Actor{Subject: in.Assistant}, + c := appClaims{ + Claims: claims.Claims{ + RegisteredClaims: i.base(in.Subject, in.Audience, in.TTL), + Scope: strings.Join(in.Scopes, " "), + LoA: in.LoA, + LoginMethod: in.LoginMethod, + Tenant: in.Tenant, + ClientID: in.ClientID, + Act: &claims.Actor{Subject: in.Assistant}, + }, + SID: in.Connection, + } + + tok, err := i.km.SignTyped(c, typeAccessToken) + if err != nil { + return "", 0, err } - return i.sign(c, in.TTL) + return tok, int64(in.TTL.Seconds()), nil } // DelegatedTokenInput describes an on-behalf-of token minted via token @@ -184,14 +204,16 @@ func (i *Issuer) IssueDelegated(in DelegatedTokenInput) (string, int64, error) { // audience is not checked here: a subject token's audience is the previous hop // (e.g. the portal API), not this endpoint, and which hops a client may act from // is the registry's to say, so the exchange checks it (registry.MayActFrom). -func (i *Issuer) ParseSubjectToken(raw string) (*claims.Claims, error) { +// Beside the claims it answers the connection the token names: an AI app's +// token's sid, "" for every other token. +func (i *Issuer) ParseSubjectToken(raw string) (*claims.Claims, string, error) { parser := jwt.NewParser( jwt.WithValidMethods([]string{i.km.Alg()}), jwt.WithIssuer(i.issuerURL), jwt.WithExpirationRequired(), ) - var c claims.Claims + var c appClaims if _, err := parser.ParseWithClaims(raw, &c, func(tok *jwt.Token) (any, error) { // Only an access token is exchanged; an ID token signed with the same // key is refused by its type [RFC 9068 §5]. @@ -206,10 +228,10 @@ func (i *Issuer) ParseSubjectToken(raw string) (*claims.Claims, error) { return pk, nil }); err != nil { - return nil, err + return nil, "", err } - return &c, nil + return &c.Claims, c.SID, nil } func (i *Issuer) base(subject, audience string, ttl time.Duration) jwt.RegisteredClaims { diff --git a/issuer/issuer_test.go b/issuer/issuer_test.go index 3412329..f96b205 100644 --- a/issuer/issuer_test.go +++ b/issuer/issuer_test.go @@ -218,10 +218,10 @@ func TestAnIDTokenIsNoSubjectTokenForAnExchange(t *testing.T) { if typ := headerType(t, id); typ != "JWT" { t.Errorf("the ID token is typed %q, want JWT", typ) } - if _, err := iss.ParseSubjectToken(access); err != nil { + if _, _, err := iss.ParseSubjectToken(access); err != nil { t.Errorf("the access token was refused as a subject: %v", err) } - if _, err := iss.ParseSubjectToken(id); err == nil { + if _, _, err := iss.ParseSubjectToken(id); err == nil { t.Error("the ID token was accepted as the subject of an exchange") } } diff --git a/routes/aiapp.go b/routes/aiapp.go index 5ad29d8..0044354 100644 --- a/routes/aiapp.go +++ b/routes/aiapp.go @@ -6,7 +6,10 @@ import ( "net/url" "slices" "strings" + "time" + "github.com/gmb-lib/go-authbyte/claims" + pkerrors "github.com/gmb-lib/go-platform-kit/errors" "github.com/go-make-bytes/authbyte/identity" "github.com/go-make-bytes/authbyte/issuer" "github.com/go-make-bytes/authbyte/registry" @@ -346,6 +349,10 @@ func (r *router) appCodeExchange(ctx *azugo.Context, app registry.SignInClient) refresh := randomToken(refreshTokenBytes) sess.RefreshKey = refreshKey(refresh) + // The connection is made now, when the app first holds its tokens: it gets + // its public name, and its assistant's index lists it until its end. + sess.SID = randomToken(24) + sess.ConnectedAt = clock().UTC().Truncate(time.Second) if err := r.Session().SaveRefresh(ctx, sess.RefreshKey, &session.RefreshGrant{ SessionID: appCode.SessionID, ClientID: app.ClientID, @@ -359,6 +366,12 @@ func (r *router) appCodeExchange(ctx *azugo.Context, app registry.SignInClient) return } + if err := r.Session().AddConnection(ctx, sess.Tenant, sess.Assistant, + session.Connection{ID: sess.SID, SessionID: appCode.SessionID}, sess.ExpiresAt); err != nil { + storeRefusal(ctx, err) + + return + } r.answerAppToken(ctx, app, sess, scopes, refresh) } @@ -530,11 +543,106 @@ func (r *router) endConnection(ctx *azugo.Context, sid string, sess *session.Ses return false } } + // Out of its assistant's index too. The session is gone, so a failure here + // leaves only a name that leads nowhere: a list skips it and drops it. + if sess.SID != "" { + if err := r.Session().RemoveConnection(ctx, sess.Tenant, sess.Assistant, + session.Connection{ID: sess.SID, SessionID: sid}); err != nil { + ctx.Log().Warn("an ended connection stays in its assistant's index: " + err.Error()) + } + } r.Audit().SessionEnded(ctx, sess.Subject, identity.LoginAssistant) return true } +// appConnectionLive reports whether an AI app's token, presented at an exchange +// by client, belongs to a connection still live: the one its sid names, in its +// assistant's index, its session there and still the token's person's, app's +// and assistant's. A connection signed out or ended is refused at once, though +// the token has not expired. A live one is marked used, at most once a minute. +// ok is false when the answer is already written. +func (r *router) appConnectionLive(ctx *azugo.Context, client string, subject *claims.Claims, connection string) bool { + // Refused as an unusable subject token is, with its own code, so the app's + // server can tell the app to sign in again rather than to try again later. + refuse := func(reason string) bool { + r.Audit().DelegationRefused(ctx, client, subject.Subject, reason) + ctx.Error(pkerrors.NewProblem("err:connection:ended", pkerrors.WithStatus(fasthttp.StatusUnauthorized), + pkerrors.WithTitle("The AI app's connection has ended; it must sign in again"))) + + return false + } + + if !r.isAIApp(subject.ClientID) { + return refuse("the AI app is no longer enabled") + } + assistant := "" + if subject.Act != nil { + assistant = subject.Act.Subject + } + if connection == "" || assistant == "" || subject.Tenant == "" { + return refuse("an AI app's token names no connection") + } + + found, sess, ok := r.findConnection(ctx, subject.Tenant, assistant, connection) + if !ok { + return false + } + if found == "" || sess.Subject != subject.Subject || sess.ClientID != subject.ClientID { + return refuse("the AI app's connection has ended") + } + + if now := clock().UTC(); now.Sub(sess.LastUsed) >= time.Minute { + sess.LastUsed = now.Truncate(time.Second) + if err := r.Session().ReplaceSession(ctx, found, sess); err != nil { + if errors.Is(err, session.ErrNotFound) { + return refuse("the AI app's connection has ended") + } + storeRefusal(ctx, err) + + return false + } + } + + return true +} + +// findConnection answers the session key and session of the connection named +// connection in an assistant's index in tenant: "" when there is none live. A +// name whose session has ended is dropped from the index on the way. ok is false +// when the store could not answer, and the answer, 503, is then written. +func (r *router) findConnection(ctx *azugo.Context, tenant, assistant, connection string) (string, *session.Session, bool) { + conns, err := r.Session().Connections(ctx, tenant, assistant) + if err != nil { + storeRefusal(ctx, err) + + return "", nil, false + } + for _, c := range conns { + if c.ID != connection { + continue + } + sess, err := r.Session().LoadSession(ctx, c.SessionID) + if errors.Is(err, session.ErrNotFound) { + _ = r.Session().RemoveConnection(ctx, tenant, assistant, c) + + return "", nil, true + } + if err != nil { + storeRefusal(ctx, err) + + return "", nil, false + } + if sess.Assistant != assistant || sess.Tenant != tenant || sess.SID != connection { + return "", nil, true + } + + return c.SessionID, sess, true + } + + return "", nil, true +} + // answerAppToken mints and answers an AI app's token: the person's, through the // assistant, for the app's one resource, with the lowest assurance. func (r *router) answerAppToken(ctx *azugo.Context, app registry.SignInClient, sess *session.Session, scopes []string, refresh string) { @@ -547,6 +655,7 @@ func (r *router) answerAppToken(ctx *azugo.Context, app registry.SignInClient, s Assistant: sess.Assistant, LoA: identity.LoALow, LoginMethod: identity.LoginAssistant, + Connection: sess.SID, TTL: r.Config().AppTokenTTL, }) if err != nil { diff --git a/routes/aiapp_test.go b/routes/aiapp_test.go index 99ea48f..6ee98bc 100644 --- a/routes/aiapp_test.go +++ b/routes/aiapp_test.go @@ -102,17 +102,17 @@ func personKeyOf(oid string) string { return rolebyte.PersonKey("sub-of-" + oid) var ( annasFirst = rolebyte.Assistant{ TenantID: "01TENANTA0000000000000000A", TenantName: "Go Make Bytes", - Key: "svc:assistant-01ASS1STANT000000000000000A", Name: "Assistant 2", + Key: "svc:assistant-01ASS1STANT00000000000000A", Name: "Assistant 2", Scopes: []string{"projects/project:view", "projects/task:view", "projects/task:create", "projects/task/comment:add"}, } annasSecond = rolebyte.Assistant{ TenantID: "01TENANTB0000000000000000B", TenantName: "Kalēji", - Key: "svc:assistant-01ASS1STANT000000000000000B", Name: "Asistents", + Key: "svc:assistant-01ASS1STANT00000000000000B", Name: "Asistents", Scopes: []string{"projects/task:view"}, } janissOwn = rolebyte.Assistant{ TenantID: "01TENANTA0000000000000000A", TenantName: "Go Make Bytes", - Key: "svc:assistant-01ASS1STANT000000000000000J", Name: "Assistant 3", + Key: "svc:assistant-01ASS1STANT00000000000000J", Name: "Assistant 3", Scopes: aiBoxes, } ) @@ -135,7 +135,7 @@ type aiDeployment struct { events *eventLog } -func aiApp(t *testing.T) *aiDeployment { +func aiApp(t *testing.T, extra ...func(*authbytecore.App)) *aiDeployment { t.Helper() d := &aiDeployment{ @@ -158,6 +158,9 @@ func aiApp(t *testing.T) *aiDeployment { app.SetScopeResolver(d.register) recordingAudit(d.events)(app) qt.Assert(t, qt.IsNil(Init(app))) + for _, f := range extra { + f(app) + } d.core = app d.app = azugo.NewTestApp(app.App) diff --git a/routes/connections.go b/routes/connections.go new file mode 100644 index 0000000..dccb998 --- /dev/null +++ b/routes/connections.go @@ -0,0 +1,320 @@ +package routes + +import ( + "errors" + "regexp" + "slices" + "strings" + "time" + + "github.com/gmb-lib/go-authbyte/claims" + pkerrors "github.com/gmb-lib/go-platform-kit/errors" + "github.com/go-make-bytes/authbyte/rolebyte" + "github.com/go-make-bytes/authbyte/session" + + "azugo.io/azugo" + "github.com/valyala/fasthttp" +) + +// The AI apps connected as assistants, behind the identity door: a person lists +// the apps connected as their own assistants in the workspace their token names +// and signs one out; an administrator of that workspace does the same for any of +// its assistants, and ends every app of one when it is removed. Each answer +// names a connection by its public name, never its session's key or a token. +// Only a person's own token is taken: an AI app's, or one another service +// obtained to act for the person, neither lists nor signs out. + +// scopeGroupMembership and scopeLevelAdministrator are the membership register's +// administering level, which a workspace's administrator holds there. +const ( + scopeGroupMembership = "membership" + scopeLevelAdministrator = "admin" +) + +// assistantKey is the shape of an assistant's key: `svc:assistant-`. +var assistantKey = regexp.MustCompile(`^svc:assistant-[0-9A-HJKMNP-TV-Z]{26}$`) + +// connectionLine is one connected AI app: its public name, the app's own name, +// when it connected and when it was last used (null until a call went through). +type connectionLine struct { + ID string `json:"id"` + App string `json:"app"` + ConnectedAt string `json:"connectedAt"` + LastUsed *string `json:"lastUsed"` +} + +// ownAssistant is one of the person's own assistants in the workspace, with the +// apps connected as it. +type ownAssistant struct { + Key string `json:"key"` + Name string `json:"name"` + Connections []connectionLine `json:"connections"` +} + +func connectionRefused(ctx *azugo.Context, status int, code, title string) { + noStore(ctx) + ctx.Error(pkerrors.NewProblem(code, pkerrors.WithStatus(status), pkerrors.WithTitle(title))) +} + +func connectionNotFound(ctx *azugo.Context) { + connectionRefused(ctx, fasthttp.StatusNotFound, "err:connection:not_found", "No such connected app") +} + +// connectionCaller answers the person a request comes from and the workspace +// their token names: a person's own token only, never an AI app's, a service's, +// or one obtained to act for the person. ok is false when the refusal is written. +func (r *router) connectionCaller(ctx *azugo.Context) (string, string, bool) { + u := ctx.User() + person, tenant := u.ID(), u.ClaimValue(claims.ClaimTenant) + if person == "" || tenant == "" || strings.HasPrefix(person, servicePrefix) || + strings.TrimSpace(u.ClaimValue(claims.ClaimAct)) != "" || r.isAIApp(u.ClaimValue(claims.ClaimClientID)) { + connectionRefused(ctx, fasthttp.StatusForbidden, "err:connection:forbidden", + "Only a person signed in to a workspace sees or signs out its connected apps") + + return "", "", false + } + + return person, tenant, true +} + +// administrator answers the workspace of a request from its administrator, and +// the assistant its address names. ok is false when the refusal is written. +func (r *router) administrator(ctx *azugo.Context) (string, string, string, bool) { + person, tenant, ok := r.connectionCaller(ctx) + if !ok { + return "", "", "", false + } + if !ctx.User().HasScopeLevel(scopeGroupMembership, scopeLevelAdministrator) { + connectionRefused(ctx, fasthttp.StatusForbidden, "err:connection:forbidden", + "Only an administrator of the workspace sees or signs out an assistant's connected apps") + + return "", "", "", false + } + assistant := ctx.Params.String("assistant") + if !assistantKey.MatchString(assistant) { + connectionNotFound(ctx) + + return "", "", "", false + } + + return person, tenant, assistant, true +} + +// ownAssistants answers the person's own assistants in tenant, from the +// register. ok is false when the register could not answer and that is written. +func (r *router) ownAssistants(ctx *azugo.Context, person, tenant string) ([]rolebyte.Assistant, bool) { + all, err := r.personsAssistants(ctx, person) + if err != nil { + r.registerUnavailable(ctx, rolebyte.PersonKey(person), err) + + return nil, false + } + + own := make([]rolebyte.Assistant, 0, len(all)) + for _, a := range all { + if a.TenantID == tenant { + own = append(own, a) + } + } + + return own, true +} + +// connectionLines answers the live apps connected as assistant in tenant, newest +// first; person, when named, keeps only that person's. ok is false when the +// store could not answer and that is written. +func (r *router) connectionLines(ctx *azugo.Context, tenant, assistant, person string) ([]connectionLine, bool) { + conns, err := r.Session().Connections(ctx, tenant, assistant) + if err != nil { + storeRefusal(ctx, err) + + return nil, false + } + + type dated struct { + at time.Time + line connectionLine + } + var found []dated + for _, c := range conns { + sess, err := r.Session().LoadSession(ctx, c.SessionID) + if errors.Is(err, session.ErrNotFound) { + _ = r.Session().RemoveConnection(ctx, tenant, assistant, c) + + continue + } + if err != nil { + storeRefusal(ctx, err) + + return nil, false + } + if sess.Tenant != tenant || sess.Assistant != assistant || sess.SID != c.ID || (person != "" && sess.Subject != person) { + continue + } + + line := connectionLine{ID: c.ID, App: sess.ClientID, ConnectedAt: sess.ConnectedAt.UTC().Format(time.RFC3339)} + if app, ok := r.Registry().AIApp(sess.ClientID); ok { + line.App = appName(app) + } + if !sess.LastUsed.IsZero() { + used := sess.LastUsed.UTC().Format(time.RFC3339) + line.LastUsed = &used + } + found = append(found, dated{at: sess.ConnectedAt, line: line}) + } + slices.SortStableFunc(found, func(a, b dated) int { return b.at.Compare(a.at) }) + + lines := make([]connectionLine, 0, len(found)) + for _, d := range found { + lines = append(lines, d.line) + } + + return lines, true +} + +// signOut ends one connection and records who did it. ok is false when the +// store could not end it and that is written. +func (r *router) signOut(ctx *azugo.Context, by, sid string, sess *session.Session, administrator bool) bool { + if !r.endConnection(ctx, sid, sess) { + return false + } + r.Audit().ConnectionSignedOut(ctx, by, sess.Subject, sess.ClientID, administrator) + + return true +} + +// ownConnections answers the person's own assistants in the workspace, each with +// the apps connected as it; an assistant with none is listed with none. +// +// @route /identity/connections [get]. +func (r *router) ownConnections(ctx *azugo.Context) { + person, tenant, ok := r.connectionCaller(ctx) + if !ok { + return + } + own, ok := r.ownAssistants(ctx, person, tenant) + if !ok { + return + } + + out := make([]ownAssistant, 0, len(own)) + for _, a := range own { + lines, ok := r.connectionLines(ctx, tenant, a.Key, person) + if !ok { + return + } + out = append(out, ownAssistant{Key: a.Key, Name: a.Name, Connections: lines}) + } + + noStore(ctx) + ctx.JSON(map[string]any{"assistants": out}) +} + +// signOutOwnConnection signs out one of the person's own connected apps, by its +// public name: it stops at once; the others go on. +// +// @route /identity/connections/{id} [delete]. +func (r *router) signOutOwnConnection(ctx *azugo.Context) { + person, tenant, ok := r.connectionCaller(ctx) + if !ok { + return + } + own, ok := r.ownAssistants(ctx, person, tenant) + if !ok { + return + } + + id := ctx.Params.String("id") + for _, a := range own { + sid, sess, ok := r.findConnection(ctx, tenant, a.Key, id) + if !ok { + return + } + if sid == "" || sess.Subject != person { + continue + } + if r.signOut(ctx, person, sid, sess, false) { + noStore(ctx) + ctx.StatusCode(fasthttp.StatusNoContent) + } + + return + } + + connectionNotFound(ctx) +} + +// assistantConnections answers, to an administrator of the workspace, the apps +// connected as one of its assistants. +// +// @route /identity/assistants/{assistant}/connections [get]. +func (r *router) assistantConnections(ctx *azugo.Context) { + _, tenant, assistant, ok := r.administrator(ctx) + if !ok { + return + } + lines, ok := r.connectionLines(ctx, tenant, assistant, "") + if !ok { + return + } + + noStore(ctx) + ctx.JSON(map[string]any{"connections": lines}) +} + +// signOutAssistantConnection signs out, for an administrator of the workspace, +// one app connected as one of its assistants. +// +// @route /identity/assistants/{assistant}/connections/{id} [delete]. +func (r *router) signOutAssistantConnection(ctx *azugo.Context) { + by, tenant, assistant, ok := r.administrator(ctx) + if !ok { + return + } + sid, sess, ok := r.findConnection(ctx, tenant, assistant, ctx.Params.String("id")) + if !ok { + return + } + if sid == "" { + connectionNotFound(ctx) + + return + } + if r.signOut(ctx, by, sid, sess, true) { + noStore(ctx) + ctx.StatusCode(fasthttp.StatusNoContent) + } +} + +// endAssistantConnections signs out, for an administrator of the workspace, +// every app connected as one of its assistants: what its removal asks first, so +// its apps stop at once rather than at their next refresh. +// +// @route /identity/assistants/{assistant}/connections [delete]. +func (r *router) endAssistantConnections(ctx *azugo.Context) { + by, tenant, assistant, ok := r.administrator(ctx) + if !ok { + return + } + conns, err := r.Session().Connections(ctx, tenant, assistant) + if err != nil { + storeRefusal(ctx, err) + + return + } + for _, c := range conns { + sid, sess, ok := r.findConnection(ctx, tenant, assistant, c.ID) + if !ok { + return + } + if sid == "" { + continue + } + if !r.signOut(ctx, by, sid, sess, true) { + return + } + } + + noStore(ctx) + ctx.StatusCode(fasthttp.StatusNoContent) +} diff --git a/routes/connections_test.go b/routes/connections_test.go new file mode 100644 index 0000000..31a21b6 --- /dev/null +++ b/routes/connections_test.go @@ -0,0 +1,575 @@ +package routes + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "net/url" + "slices" + "strings" + "testing" + "time" + + "github.com/gmb-lib/go-authbyte/claims" + authbytecore "github.com/go-make-bytes/authbyte" + "github.com/go-make-bytes/authbyte/identity" + "github.com/go-make-bytes/authbyte/issuer" + "github.com/go-make-bytes/authbyte/rolebyte" + "github.com/go-make-bytes/authbyte/session" + "github.com/go-make-bytes/authbyte/session/sessiontest" + + "azugo.io/azugo" + "azugo.io/azugo/user" + "github.com/go-quicktest/qt" + "github.com/valyala/fasthttp" +) + +// The connections' routes run behind the identity door's authentication; here +// they sit on scratch routes behind a stand-in for it, the caller's claims read +// from request headers, so the rights rules run through the real handlers. The +// door itself is proved on the stack. +func connectionRoutes(app *authbytecore.App) { + r := &router{App: app} + as := func(h azugo.RequestHandler) azugo.RequestHandler { + return func(ctx *azugo.Context) { + c := &claims.Claims{Scope: ctx.Header.Get("X-Test-Scope"), Tenant: ctx.Header.Get("X-Test-Tenant")} + c.Subject = ctx.Header.Get("X-Test-Sub") + switch ctx.Header.Get("X-Test-Kind") { + case "app": + c.ClientID = aiClient + c.Act = &claims.Actor{Subject: annasFirst.Key} + case "app-bare": + // Not one the issuer mints (an app token always names its + // assistant): the second guard, proved on its own. + c.ClientID = aiClient + case "delegated": + c.Act = &claims.Actor{Subject: "svc:flowbyte-bff"} + case "service": + c.ClientID = c.Subject + default: + c.ClientID = "plain-app" + } + ctx.SetUser(user.New(c.ToUserClaims())) + h(ctx) + } + } + app.Get("/testonly/connections", as(r.ownConnections)) + app.Delete("/testonly/connections/{id}", as(r.signOutOwnConnection)) + app.Get("/testonly/assistants/{assistant}/connections", as(r.assistantConnections)) + app.Delete("/testonly/assistants/{assistant}/connections/{id}", as(r.signOutAssistantConnection)) + app.Delete("/testonly/assistants/{assistant}/connections", as(r.endAssistantConnections)) +} + +// who is a caller of the connections' routes. +type who struct{ sub, tenant, scope, kind string } + +var ( + annaInA = who{sub: "sub-of-anna", tenant: annasFirst.TenantID} + annaInB = who{sub: "sub-of-anna", tenant: annasSecond.TenantID} + janisInA = who{sub: "sub-of-janis", tenant: janissOwn.TenantID} + // The administrator of workspace A, and one of workspace B. + adminOfA = who{sub: "sub-of-gatis", tenant: annasFirst.TenantID, scope: "membership:admin"} + adminOfB = who{sub: "sub-of-gatis", tenant: annasSecond.TenantID, scope: "membership:admin"} + // A member of A who is not its administrator. + memberOfA = who{sub: "sub-of-maris", tenant: annasFirst.TenantID, scope: "membership:people membership:self"} +) + +func (d *aiDeployment) call(t *testing.T, w who, method, path string) (int, map[string]any) { + t.Helper() + + tc := d.app.TestClient() + opts := []azugo.TestClientOption{ + tc.WithHeader("X-Test-Sub", w.sub), tc.WithHeader("X-Test-Tenant", w.tenant), + tc.WithHeader("X-Test-Scope", w.scope), tc.WithHeader("X-Test-Kind", w.kind), + } + var ( + resp *fasthttp.Response + err error + ) + if method == fasthttp.MethodDelete { + resp, err = tc.Delete("/testonly"+path, opts...) + } else { + resp, err = tc.Get("/testonly"+path, opts...) + } + qt.Assert(t, qt.IsNil(err)) + defer fasthttp.ReleaseResponse(resp) + out := map[string]any{"_body": string(resp.Body())} + _ = json.Unmarshal(resp.Body(), &out) + + return resp.StatusCode(), out +} + +// connectAs connects an AI app for the directory person oid as assistant a, and +// answers its tokens. +func (d *aiDeployment) connectAs(t *testing.T, oid string, a rolebyte.Assistant) map[string]any { + t.Helper() + + tc := d.app.TestClient() + verifier := randomToken(32) + page := d.signInAs(t, tc, oid, aiAsk(verifier, nil)) + qt.Assert(t, qt.Equals(page.status, fasthttp.StatusOK), qt.Commentf("%s", page.body)) + code := codeFrom(t, pick(t, tc, page, assistantWay(a))) + status, out := tokenAt(t, d, "/token", codeExchange(code, verifier)) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%v", out)) + + return out +} + +// toolCall is the MCP server's exchange of an app token, as one tool call makes it. +func (d *aiDeployment) toolCall(t *testing.T, appToken string) int { + t.Helper() + + status, _ := d.exchangeAt(t, "svc:flowbyte-mcp", "mcp-secret", appToken, "svc:flowbyte-integration-api", "projects/task:view") + + return status +} + +func (d *aiDeployment) refreshes(t *testing.T, tokens map[string]any) (bool, map[string]any) { + t.Helper() + + status, out := tokenAt(t, d, "/token", appRefreshForm(tokens["refresh_token"].(string))) + + return status == fasthttp.StatusOK, out +} + +// connectionsOf is the connections an answer lists for assistant key, own or not. +func connectionsOf(out map[string]any, key string) []map[string]any { + var list []any + if as, ok := out["assistants"].([]any); ok { + for _, a := range as { + if m, _ := a.(map[string]any); m["key"] == key { + list, _ = m["connections"].([]any) + } + } + } else { + list, _ = out["connections"].([]any) + } + res := make([]map[string]any, 0, len(list)) + for _, c := range list { + m, _ := c.(map[string]any) + res = append(res, m) + } + + return res +} + +func idsOf(cs []map[string]any) []string { + out := []string{} + for _, c := range cs { + out = append(out, c["id"].(string)) + } + + return out +} + +func withClock(t *testing.T, now func() time.Time) { + t.Helper() + + before := clock + clock = now + t.Cleanup(func() { clock = before }) +} + +// A person's own connections, by assistant, in the workspace +// their token names: the app by its registered name, when it connected, not used +// yet; another workspace's and another person's are not among them; an assistant +// with none is listed with none; and the id is the connection's own, never a key +// the store keeps or a refresh token. +func TestAPersonsOwnConnectionsAreListedByAssistant(t *testing.T) { + d := aiApp(t, connectionRoutes) + before := time.Now().Add(-time.Second) + one := d.connectAs(t, annasOID, annasFirst) + two := d.connectAs(t, annasOID, annasFirst) + d.connectAs(t, annasOID, annasSecond) + + status, out := d.call(t, janisInA, fasthttp.MethodGet, "/connections") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%v", out)) + as, _ := out["assistants"].([]any) + qt.Assert(t, qt.HasLen(as, 1), qt.Commentf("Jānis's own assistant, with no app yet: %v", out)) + qt.Check(t, qt.Equals(as[0].(map[string]any)["name"], any(janissOwn.Name))) + qt.Check(t, qt.HasLen(connectionsOf(out, janissOwn.Key), 0)) + d.connectAs(t, janissOID, janissOwn) + + status, out = d.call(t, annaInA, fasthttp.MethodGet, "/connections") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%v", out)) + as, _ = out["assistants"].([]any) + qt.Assert(t, qt.HasLen(as, 1), qt.Commentf("workspace A's assistant only: %v", out)) + qt.Check(t, qt.Equals(as[0].(map[string]any)["key"], any(annasFirst.Key))) + qt.Check(t, qt.Equals(as[0].(map[string]any)["name"], any(annasFirst.Name))) + listed := connectionsOf(out, annasFirst.Key) + qt.Assert(t, qt.HasLen(listed, 2)) + for _, c := range listed { + qt.Check(t, qt.Equals(c["app"], any("Claude Code"))) + qt.Check(t, qt.IsNil(c["lastUsed"]), qt.Commentf("not used yet")) + at, err := time.Parse(time.RFC3339, c["connectedAt"].(string)) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.IsTrue(at.After(before) && at.Before(time.Now().Add(time.Second))), qt.Commentf("connected now: %v", at)) + } + + // The ids are the connections' own: no key the store keeps, no token. + body := out["_body"].(string) + for key := range d.mem.Entries() { + if s, ok := strings.CutPrefix(key, "sess:"); ok { + qt.Check(t, qt.IsFalse(strings.Contains(body, s)), qt.Commentf("a session key in the answer")) + } + } + for _, tok := range []map[string]any{one, two} { + qt.Check(t, qt.IsFalse(strings.Contains(body, tok["refresh_token"].(string)))) + qt.Check(t, qt.IsFalse(strings.Contains(body, tok["access_token"].(string)))) + } + + status, out = d.call(t, annaInB, fasthttp.MethodGet, "/connections") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK)) + qt.Check(t, qt.HasLen(connectionsOf(out, annasSecond.Key), 1), qt.Commentf("workspace B's, asked with B's token: %v", out)) + qt.Check(t, qt.HasLen(connectionsOf(out, annasFirst.Key), 0)) +} + +// A tool call through the app marks the connection used; when it +// connected never moves; a second call within the minute writes nothing new. +func TestAToolCallMarksTheConnectionUsed(t *testing.T) { + d := aiApp(t, connectionRoutes) + t0 := time.Now().Truncate(time.Second) + withClock(t, func() time.Time { return t0 }) + tokens := d.connectAs(t, annasOID, annasFirst) + + withClock(t, func() time.Time { return t0.Add(10 * time.Second) }) + qt.Assert(t, qt.Equals(d.toolCall(t, tokens["access_token"].(string)), fasthttp.StatusOK)) + withClock(t, func() time.Time { return t0.Add(40 * time.Second) }) + qt.Assert(t, qt.Equals(d.toolCall(t, tokens["access_token"].(string)), fasthttp.StatusOK)) + + _, out := d.call(t, annaInA, fasthttp.MethodGet, "/connections") + c := connectionsOf(out, annasFirst.Key) + qt.Assert(t, qt.HasLen(c, 1)) + qt.Check(t, qt.Equals(c[0]["connectedAt"], any(t0.UTC().Format(time.RFC3339)))) + qt.Check(t, qt.Equals(c[0]["lastUsed"], any(t0.Add(10*time.Second).UTC().Format(time.RFC3339))), + qt.Commentf("the second call, within the minute, writes nothing")) + + withClock(t, func() time.Time { return t0.Add(80 * time.Second) }) + qt.Assert(t, qt.Equals(d.toolCall(t, tokens["access_token"].(string)), fasthttp.StatusOK)) + _, out = d.call(t, annaInA, fasthttp.MethodGet, "/connections") + c = connectionsOf(out, annasFirst.Key) + qt.Check(t, qt.Equals(c[0]["lastUsed"], any(t0.Add(80*time.Second).UTC().Format(time.RFC3339)))) + qt.Check(t, qt.Equals(c[0]["connectedAt"], any(t0.UTC().Format(time.RFC3339)))) +} + +// The person signs one of two apps out: its refresh is refused, its +// next tool call is refused at once though its token has not expired, and the +// other app goes on. +func TestAPersonSignsOneAppOutAndItStopsAtOnce(t *testing.T) { + d := aiApp(t, connectionRoutes) + one := d.connectAs(t, annasOID, annasFirst) + other := d.connectAs(t, annasOID, annasFirst) + qt.Assert(t, qt.Equals(d.toolCall(t, one["access_token"].(string)), fasthttp.StatusOK)) + + _, out := d.call(t, annaInA, fasthttp.MethodGet, "/connections") + listed := connectionsOf(out, annasFirst.Key) + qt.Assert(t, qt.HasLen(listed, 2)) + // The connection the first app holds is the one its token names. + target := readSID(t, one["access_token"].(string)) + qt.Assert(t, qt.Not(qt.Equals(target, ""))) + qt.Assert(t, qt.IsTrue(slices.Contains(idsOf(listed), target)), qt.Commentf("%v %s", idsOf(listed), target)) + + status, res := d.call(t, annaInA, fasthttp.MethodDelete, "/connections/"+url.PathEscape(target)) + qt.Assert(t, qt.Equals(status, fasthttp.StatusNoContent), qt.Commentf("%v", res)) + indexed, err := d.mem.Connections(context.Background(), annasFirst.TenantID, annasFirst.Key) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.HasLen(indexed, 1), qt.Commentf("out of its assistant's index at its end, not left for a list to drop")) + + qt.Check(t, qt.Equals(d.toolCall(t, one["access_token"].(string)), fasthttp.StatusUnauthorized), + qt.Commentf("its token is still within its lifetime, and refused")) + _, refused := d.exchangeAt(t, "svc:flowbyte-mcp", "mcp-secret", one["access_token"].(string), "svc:flowbyte-integration-api", "projects/task:view") + qt.Check(t, qt.Equals(refused["code"], any("err:connection:ended")), qt.Commentf("named, so the app is told to sign in again: %v", refused)) + ok, ans := d.refreshes(t, one) + qt.Check(t, qt.IsFalse(ok)) + qt.Check(t, qt.Equals(ans["error"], any("invalid_grant"))) + + qt.Check(t, qt.Equals(d.toolCall(t, other["access_token"].(string)), fasthttp.StatusOK), qt.Commentf("the other goes on")) + ok, _ = d.refreshes(t, other) + qt.Check(t, qt.IsTrue(ok)) + _, out = d.call(t, annaInA, fasthttp.MethodGet, "/connections") + qt.Check(t, qt.HasLen(connectionsOf(out, annasFirst.Key), 1)) +} + +// readSID is the connection an app token names. +func readSID(t *testing.T, raw string) string { + t.Helper() + + parts := strings.Split(raw, ".") + qt.Assert(t, qt.HasLen(parts, 3)) + var c struct { + SID string `json:"sid"` + } + qt.Assert(t, qt.IsNil(decodeSegment(parts[1], &c))) + + return c.SID +} + +// Another person neither sees nor signs out Anna's connection. +func TestAnotherPersonCannotSignOutAConnection(t *testing.T) { + d := aiApp(t, connectionRoutes) + annas := d.connectAs(t, annasOID, annasFirst) + target := readSID(t, annas["access_token"].(string)) + + _, out := d.call(t, janisInA, fasthttp.MethodGet, "/connections") + qt.Check(t, qt.IsFalse(strings.Contains(out["_body"].(string), target))) + + status, res := d.call(t, janisInA, fasthttp.MethodDelete, "/connections/"+url.PathEscape(target)) + qt.Check(t, qt.Equals(status, fasthttp.StatusNotFound), qt.Commentf("%v", res)) + qt.Check(t, qt.Equals(res["code"], any("err:connection:not_found"))) + qt.Check(t, qt.Equals(d.toolCall(t, annas["access_token"].(string)), fasthttp.StatusOK), qt.Commentf("Anna's goes on")) + ok, _ := d.refreshes(t, annas) + qt.Check(t, qt.IsTrue(ok)) +} + +// The workspace's administrator lists an assistant's apps and signs one +// out; the sign-out is recorded with the administrator as its doer. +func TestAnAdministratorSignsOutAnAssistantsApp(t *testing.T) { + d := aiApp(t, connectionRoutes) + one := d.connectAs(t, annasOID, annasFirst) + other := d.connectAs(t, annasOID, annasFirst) + + status, out := d.call(t, adminOfA, fasthttp.MethodGet, "/assistants/"+annasFirst.Key+"/connections") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%v", out)) + listed := connectionsOf(out, "") + qt.Assert(t, qt.HasLen(listed, 2)) + qt.Check(t, qt.Equals(listed[0]["app"], any("Claude Code"))) + + target := readSID(t, one["access_token"].(string)) + status, res := d.call(t, adminOfA, fasthttp.MethodDelete, "/assistants/"+annasFirst.Key+"/connections/"+url.PathEscape(target)) + qt.Assert(t, qt.Equals(status, fasthttp.StatusNoContent), qt.Commentf("%v", res)) + qt.Check(t, qt.Equals(d.toolCall(t, one["access_token"].(string)), fasthttp.StatusUnauthorized)) + qt.Check(t, qt.Equals(d.toolCall(t, other["access_token"].(string)), fasthttp.StatusOK)) + + ended := d.events.sharedEvents("connection_signed_out") + qt.Assert(t, qt.HasLen(ended, 1)) + qt.Check(t, qt.Equals(ended[0]["person"], any("sub-of-anna"))) + qt.Check(t, qt.Equals(ended[0]["by"], any("administrator"))) + qt.Check(t, qt.Equals(d.events.actorOf("connection_signed_out"), "sub-of-gatis")) +} + +// Only an administrator of the assistant's workspace reads or ends its +// apps: a member who is not is refused, and an administrator of another +// workspace reads nothing of this one and ends nothing. +func TestOnlyTheWorkspacesAdministratorReadsAnAssistantsApps(t *testing.T) { + d := aiApp(t, connectionRoutes) + annas := d.connectAs(t, annasOID, annasFirst) + target := readSID(t, annas["access_token"].(string)) + path := "/assistants/" + annasFirst.Key + "/connections" + + for _, c := range []struct { + name string + w who + get, del, all int + }{ + {"a member who is not the administrator", memberOfA, fasthttp.StatusForbidden, fasthttp.StatusForbidden, fasthttp.StatusForbidden}, + {"the person herself, on the administrator's route", annaInA, fasthttp.StatusForbidden, fasthttp.StatusForbidden, fasthttp.StatusForbidden}, + // Workspace B's index of that key is empty: B reads none and ends none of A's. + {"another workspace's administrator", adminOfB, fasthttp.StatusOK, fasthttp.StatusNotFound, fasthttp.StatusNoContent}, + } { + status, out := d.call(t, c.w, fasthttp.MethodGet, path) + qt.Check(t, qt.Equals(status, c.get), qt.Commentf("%s: %v", c.name, out)) + qt.Check(t, qt.HasLen(connectionsOf(out, ""), 0), qt.Commentf("%s reads nothing", c.name)) + status, _ = d.call(t, c.w, fasthttp.MethodDelete, path+"/"+url.PathEscape(target)) + qt.Check(t, qt.Equals(status, c.del), qt.Commentf("%s", c.name)) + status, _ = d.call(t, c.w, fasthttp.MethodDelete, path) + qt.Check(t, qt.Equals(status, c.all), qt.Commentf("%s", c.name)) + qt.Check(t, qt.Equals(d.toolCall(t, annas["access_token"].(string)), fasthttp.StatusOK), qt.Commentf("%s ended nothing", c.name)) + } + qt.Check(t, qt.HasLen(d.events.sharedEvents("connection_signed_out"), 0)) +} + +// Ending every app of an assistant (its removal) ends its own, at once, +// and nobody else's. +func TestEndingAnAssistantsAppsEndsOnlyItsOwn(t *testing.T) { + d := aiApp(t, connectionRoutes) + one := d.connectAs(t, annasOID, annasFirst) + two := d.connectAs(t, annasOID, annasFirst) + inB := d.connectAs(t, annasOID, annasSecond) + janis := d.connectAs(t, janissOID, janissOwn) + + status, res := d.call(t, adminOfA, fasthttp.MethodDelete, "/assistants/"+annasFirst.Key+"/connections") + qt.Assert(t, qt.Equals(status, fasthttp.StatusNoContent), qt.Commentf("%v", res)) + for _, tok := range []map[string]any{one, two} { + qt.Check(t, qt.Equals(d.toolCall(t, tok["access_token"].(string)), fasthttp.StatusUnauthorized)) + ok, _ := d.refreshes(t, tok) + qt.Check(t, qt.IsFalse(ok)) + } + for _, tok := range []map[string]any{inB, janis} { + qt.Check(t, qt.Equals(d.toolCall(t, tok["access_token"].(string)), fasthttp.StatusOK)) + } + qt.Check(t, qt.HasLen(d.events.sharedEvents("connection_signed_out"), 2)) + + status, _ = d.call(t, adminOfA, fasthttp.MethodDelete, "/assistants/"+annasFirst.Key+"/connections") + qt.Check(t, qt.Equals(status, fasthttp.StatusNoContent), qt.Commentf("an assistant with none: nothing to end")) +} + +// A sign-out sent twice, and an id that never was, are not found and +// end nothing else. +func TestASignOutSentTwiceIsNotFound(t *testing.T) { + d := aiApp(t, connectionRoutes) + one := d.connectAs(t, annasOID, annasFirst) + other := d.connectAs(t, annasOID, annasFirst) + target := readSID(t, one["access_token"].(string)) + + status, _ := d.call(t, annaInA, fasthttp.MethodDelete, "/connections/"+url.PathEscape(target)) + qt.Assert(t, qt.Equals(status, fasthttp.StatusNoContent)) + status, _ = d.call(t, annaInA, fasthttp.MethodDelete, "/connections/"+url.PathEscape(target)) + qt.Check(t, qt.Equals(status, fasthttp.StatusNotFound)) + status, _ = d.call(t, annaInA, fasthttp.MethodDelete, "/connections/never-a-connection") + qt.Check(t, qt.Equals(status, fasthttp.StatusNotFound)) + qt.Check(t, qt.Equals(d.toolCall(t, other["access_token"].(string)), fasthttp.StatusOK)) + qt.Check(t, qt.HasLen(d.events.sharedEvents("connection_signed_out"), 1)) +} + +// A connection is listed a second before its sign-in's session ends and +// not at its end. +func TestAConnectionIsListedUntilItsSessionEnds(t *testing.T) { + d := aiApp(t, connectionRoutes) + start := time.Now() + d.mem.SetClock(func() time.Time { return start }) + d.connectAs(t, annasOID, annasFirst) + + d.mem.SetClock(func() time.Time { return start.Add(sessionLifetime - time.Second) }) + _, out := d.call(t, annaInA, fasthttp.MethodGet, "/connections") + qt.Check(t, qt.HasLen(connectionsOf(out, annasFirst.Key), 1), qt.Commentf("a second before its end")) + + d.mem.SetClock(func() time.Time { return start.Add(sessionLifetime) }) + _, out = d.call(t, annaInA, fasthttp.MethodGet, "/connections") + qt.Check(t, qt.HasLen(connectionsOf(out, annasFirst.Key), 0), qt.Commentf("at its end")) +} + +// A sign-in that is not an AI app's is never a connection: its session's +// public name signs nothing out. +func TestABrowserSignInIsNeverAConnection(t *testing.T) { + d := aiApp(t, connectionRoutes) + browser := &session.Session{Subject: "sub-of-anna", ClientID: "plain-app", Tenant: annasFirst.TenantID, SID: "browser-public-name"} + qt.Assert(t, qt.IsNil(d.mem.CreateSession(context.Background(), "browser-session", browser, time.Hour))) + + _, out := d.call(t, annaInA, fasthttp.MethodGet, "/connections") + qt.Check(t, qt.IsFalse(strings.Contains(out["_body"].(string), "browser-public-name"))) + status, _ := d.call(t, annaInA, fasthttp.MethodDelete, "/connections/browser-public-name") + qt.Check(t, qt.Equals(status, fasthttp.StatusNotFound)) + _, err := d.mem.LoadSession(context.Background(), "browser-session") + qt.Check(t, qt.IsNil(err), qt.Commentf("the browser's session stays")) +} + +// An AI app's own token, a token another service obtained to act for the +// person, and a service's own token neither list nor sign out. +func TestOnlyAPersonsOwnTokenListsOrSignsOut(t *testing.T) { + d := aiApp(t, connectionRoutes) + annas := d.connectAs(t, annasOID, annasFirst) + target := readSID(t, annas["access_token"].(string)) + + for _, w := range []who{ + {sub: "sub-of-anna", tenant: annasFirst.TenantID, kind: "app"}, + {sub: "sub-of-anna", tenant: annasFirst.TenantID, kind: "app-bare"}, + {sub: "sub-of-anna", tenant: annasFirst.TenantID, kind: "delegated"}, + {sub: "svc:flowbyte-bff", tenant: annasFirst.TenantID, kind: "service", scope: "membership:admin"}, + {sub: "sub-of-anna", kind: "person"}, + } { + status, out := d.call(t, w, fasthttp.MethodGet, "/connections") + qt.Check(t, qt.Equals(status, fasthttp.StatusForbidden), qt.Commentf("%v: %v", w, out)) + qt.Check(t, qt.Equals(out["code"], any("err:connection:forbidden"))) + status, _ = d.call(t, w, fasthttp.MethodDelete, "/connections/"+url.PathEscape(target)) + qt.Check(t, qt.Equals(status, fasthttp.StatusForbidden), qt.Commentf("%v", w)) + w.scope = "membership:admin" + status, _ = d.call(t, w, fasthttp.MethodGet, "/assistants/"+annasFirst.Key+"/connections") + qt.Check(t, qt.Equals(status, fasthttp.StatusForbidden), qt.Commentf("%v", w)) + } + qt.Check(t, qt.Equals(d.toolCall(t, annas["access_token"].(string)), fasthttp.StatusOK)) +} + +// A store or a register that cannot answer is said so, +// and nothing is claimed ended. +func TestAStoreOrRegisterThatCannotAnswerIsSaidSo(t *testing.T) { + d := aiApp(t, connectionRoutes) + annas := d.connectAs(t, annasOID, annasFirst) + target := readSID(t, annas["access_token"].(string)) + + d.register.assistantsErr = errors.New("register down") + status, out := d.call(t, annaInA, fasthttp.MethodGet, "/connections") + qt.Check(t, qt.Equals(status, fasthttp.StatusBadGateway), qt.Commentf("%v", out)) + qt.Check(t, qt.Equals(out["code"], any("err:upstream:unavailable"))) + status, _ = d.call(t, annaInA, fasthttp.MethodDelete, "/connections/"+url.PathEscape(target)) + qt.Check(t, qt.Equals(status, fasthttp.StatusBadGateway)) + d.register.assistantsErr = nil + + d.core.SetSessionStore(failingStore{d.mem}) + status, out = d.call(t, adminOfA, fasthttp.MethodGet, "/assistants/"+annasFirst.Key+"/connections") + qt.Check(t, qt.Equals(status, fasthttp.StatusServiceUnavailable), qt.Commentf("%v", out)) + qt.Check(t, qt.Equals(out["code"], any("err:upstream:unavailable"))) + status, _ = d.call(t, adminOfA, fasthttp.MethodDelete, "/assistants/"+annasFirst.Key+"/connections/"+url.PathEscape(target)) + qt.Check(t, qt.Equals(status, fasthttp.StatusServiceUnavailable)) + status, _ = d.exchangeAt(t, "svc:flowbyte-mcp", "mcp-secret", annas["access_token"].(string), "svc:flowbyte-integration-api", "projects/task:view") + qt.Check(t, qt.Equals(status, fasthttp.StatusServiceUnavailable), qt.Commentf("the exchange cannot tell the connection is live")) + d.core.SetSessionStore(d.mem) + + qt.Check(t, qt.Equals(d.toolCall(t, annas["access_token"].(string)), fasthttp.StatusOK), qt.Commentf("nothing ended")) +} + +// failingStore is the session store whose index of connections cannot answer. +type failingStore struct{ *sessiontest.Memory } + +func (failingStore) Connections(context.Context, string, string) ([]session.Connection, error) { + return nil, errors.New("store down") +} + +// An app token naming no connection (one made before connections were +// named): refused at the exchange, as no live connection can be found for it. +func TestAnAppTokenNamingNoConnectionIsNotExchanged(t *testing.T) { + d := aiApp(t, connectionRoutes) + d.connectAs(t, annasOID, annasFirst) + tok, _, err := d.core.Issuer().IssueApp(issuer.AppTokenInput{ + Subject: "sub-of-anna", Audience: aiResource, ClientID: aiClient, Scopes: annasFirst.Scopes, + Tenant: annasFirst.TenantID, Assistant: annasFirst.Key, LoA: identity.LoALow, + LoginMethod: identity.LoginAssistant, TTL: time.Minute, + }) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.Equals(readSID(t, tok), "")) + + qt.Check(t, qt.Equals(d.toolCall(t, tok), fasthttp.StatusUnauthorized)) +} + +// An AI app's token is checked by what it is, not by the +// registry; the token of an app no longer enabled there is refused though its +// connection is named and live, rather than exchanged unchecked. +func TestTheTokenOfAnAppNoLongerEnabledIsNotExchanged(t *testing.T) { + d := aiApp(t, connectionRoutes) + live := d.connectAs(t, annasOID, annasFirst) + tok, _, err := d.core.Issuer().IssueApp(issuer.AppTokenInput{ + Subject: "sub-of-anna", Audience: aiResource, ClientID: "a-retired-app", Scopes: annasFirst.Scopes, + Tenant: annasFirst.TenantID, Assistant: annasFirst.Key, LoA: identity.LoALow, + LoginMethod: identity.LoginAssistant, Connection: readSID(t, live["access_token"].(string)), TTL: time.Minute, + }) + qt.Assert(t, qt.IsNil(err)) + + status, out := d.exchangeAt(t, "svc:flowbyte-mcp", "mcp-secret", tok, "svc:flowbyte-integration-api", "projects/task:view") + qt.Check(t, qt.Equals(status, fasthttp.StatusUnauthorized), qt.Commentf("%v", out)) + qt.Check(t, qt.Equals(out["code"], any("err:connection:ended"))) + qt.Check(t, qt.Equals(d.toolCall(t, live["access_token"].(string)), fasthttp.StatusOK), qt.Commentf("the enabled app's own goes on")) +} + +// decodeSegment reads one part of a token. +func decodeSegment(seg string, v any) error { + b, err := base64.RawURLEncoding.DecodeString(seg) + if err != nil { + return err + } + + return json.Unmarshal(b, v) +} + +// actorOf is the doer of the first recorded event of kind. +func (l *eventLog) actorOf(kind string) string { + l.mu.Lock() + defer l.mu.Unlock() + + for _, ev := range l.events { + if ev.Attributes["kind"] == kind && ev.Actor != nil { + return ev.Actor.ID + } + } + + return "" +} diff --git a/routes/router.go b/routes/router.go index 5c16e57..754f14f 100644 --- a/routes/router.go +++ b/routes/router.go @@ -95,6 +95,13 @@ func Init(a *authbytecore.App) error { identityGroup.Post("/persons", r.registerPerson) identityGroup.Post("/persons/lines", r.personLines) identityGroup.Get("/persons/{personSub}/code", r.personCode) + // The AI apps connected as assistants: a person's own, and, for a workspace's + // administrator, an assistant's. + identityGroup.Get("/connections", r.ownConnections) + identityGroup.Delete("/connections/{id}", r.signOutOwnConnection) + identityGroup.Get("/assistants/{assistant}/connections", r.assistantConnections) + identityGroup.Delete("/assistants/{assistant}/connections/{id}", r.signOutAssistantConnection) + identityGroup.Delete("/assistants/{assistant}/connections", r.endAssistantConnections) // Development conveniences (guarded by configuration; never on in prod). if dir := a.Config().DemoDir; dir != "" { diff --git a/routes/shared_test.go b/routes/shared_test.go index ab99b30..d044d27 100644 --- a/routes/shared_test.go +++ b/routes/shared_test.go @@ -721,7 +721,7 @@ func TestASignOutEndsEveryAppOfTheSharedSession(t *testing.T) { // 7: an access token already issued is still accepted where this authority // accepts one (the token exchange's subject token), to its own end, at most a // user token's lifetime after it was issued. - _, err = core.Issuer().ParseSubjectToken(second.access) + _, _, err = core.Issuer().ParseSubjectToken(second.access) qt.Check(t, qt.IsNil(err)) claims := tokenClaims(t, second.access) lifetime := time.Duration(claims["exp"].(float64)-claims["iat"].(float64)) * time.Second diff --git a/routes/token.go b/routes/token.go index 4fd8294..7038e85 100644 --- a/routes/token.go +++ b/routes/token.go @@ -684,7 +684,7 @@ func (r *router) grantTokenExchange(ctx *azugo.Context, thumbprint string) { // The presented subject token must be one this issuer minted and still // valid; its subject names the user being acted for. - subject, err := r.Issuer().ParseSubjectToken(subjectToken) + subject, connection, err := r.Issuer().ParseSubjectToken(subjectToken) if err != nil { ctx.Error(corehttp.UnauthorizedError{}) @@ -715,6 +715,16 @@ func (r *router) grantTokenExchange(ctx *azugo.Context, thumbprint string) { return } + // An AI app's token stops at once when its connection ends, though it has not + // expired: it is exchanged only while the connection it names is live. It is + // known by what it is (the assistant's way, and the app's own client id, which + // a token made by an exchange never names), not by the registry, so an app no + // longer enabled there is refused rather than exchanged unchecked. + if subject.LoginMethod == identity.LoginAssistant && subject.ClientID != "" && + !r.appConnectionLive(ctx, clientID, subject, connection) { + return + } + // The target audience + scopes are authorized against the same grant matrix // that governs client-credentials. scopes, err := r.Registry().AllowedScopes(clientID, audience, requested) diff --git a/session/connections_test.go b/session/connections_test.go new file mode 100644 index 0000000..4f1a69e --- /dev/null +++ b/session/connections_test.go @@ -0,0 +1,127 @@ +package session_test + +import ( + "context" + "slices" + "testing" + "time" + + "github.com/go-make-bytes/authbyte/session" + "github.com/go-make-bytes/authbyte/session/sessiontest" + + "github.com/go-quicktest/qt" +) + +// connectionStore is what the connections' contract checks: the index of the AI +// apps connected as each assistant. +type connectionStore interface { + AddConnection(ctx context.Context, tenant, assistant string, c session.Connection, until time.Time) error + Connections(ctx context.Context, tenant, assistant string) ([]session.Connection, error) + RemoveConnection(ctx context.Context, tenant, assistant string, c session.Connection) error +} + +func bothConnectionStores(t *testing.T, check func(t *testing.T, s connectionStore)) { + t.Helper() + + t.Run("valkey", func(t *testing.T) { check(t, valkeyStore(t)) }) + t.Run("memory", func(t *testing.T) { check(t, sessiontest.NewMemory()) }) +} + +const ( + tenantA = "01TENANTA0000000000000000A" + tenantB = "01TENANTB0000000000000000B" + assistant1 = "svc:assistant-01ASS1STANT000000000000000A" + assistant2 = "svc:assistant-01ASS1STANT000000000000000B" +) + +func ids(cs []session.Connection) []string { + out := make([]string, 0, len(cs)) + for _, c := range cs { + out = append(out, c.ID+"="+c.SessionID) + } + slices.Sort(out) + + return out +} + +// An assistant's connections are kept by workspace and assistant: each is listed +// under its own pair only, and a removed one is gone while the others stay. +func TestConnectionsAreKeptPerWorkspaceAndAssistant(t *testing.T) { + bothConnectionStores(t, func(t *testing.T, s connectionStore) { + ctx := context.Background() + until := time.Now().Add(time.Hour) + one := session.Connection{ID: "public-1", SessionID: "sid-1"} + two := session.Connection{ID: "public-2", SessionID: "sid-2"} + other := session.Connection{ID: "public-3", SessionID: "sid-3"} + elsewhere := session.Connection{ID: "public-4", SessionID: "sid-4"} + + qt.Assert(t, qt.IsNil(s.AddConnection(ctx, tenantA, assistant1, one, until))) + qt.Assert(t, qt.IsNil(s.AddConnection(ctx, tenantA, assistant1, two, until))) + qt.Assert(t, qt.IsNil(s.AddConnection(ctx, tenantA, assistant2, other, until))) + qt.Assert(t, qt.IsNil(s.AddConnection(ctx, tenantB, assistant1, elsewhere, until))) + + got, err := s.Connections(ctx, tenantA, assistant1) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.DeepEquals(ids(got), []string{"public-1=sid-1", "public-2=sid-2"})) + + got, err = s.Connections(ctx, tenantB, assistant1) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.DeepEquals(ids(got), []string{"public-4=sid-4"}), qt.Commentf("another workspace's pair is its own")) + + qt.Assert(t, qt.IsNil(s.RemoveConnection(ctx, tenantA, assistant1, one))) + qt.Assert(t, qt.IsNil(s.RemoveConnection(ctx, tenantA, assistant1, one)), qt.Commentf("removing it again is no error")) + got, err = s.Connections(ctx, tenantA, assistant1) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.DeepEquals(ids(got), []string{"public-2=sid-2"})) + + got, err = s.Connections(ctx, tenantA, "svc:assistant-01NEVERADDED0000000000000Z") + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.HasLen(got, 0), qt.Commentf("an assistant with none answers none")) + }) +} + +// A connection is listed until its end and not at it; one whose end has passed +// is never added. +func TestAConnectionIsListedUntilItsEnd(t *testing.T) { + bothConnectionStores(t, func(t *testing.T, s connectionStore) { + ctx := context.Background() + short := session.Connection{ID: "public-short", SessionID: "sid-short"} + long := session.Connection{ID: "public-long", SessionID: "sid-long"} + + qt.Assert(t, qt.IsNil(s.AddConnection(ctx, tenantA, assistant1, short, time.Now().Add(1200*time.Millisecond)))) + qt.Assert(t, qt.IsNil(s.AddConnection(ctx, tenantA, assistant1, long, time.Now().Add(time.Hour)))) + + got, err := s.Connections(ctx, tenantA, assistant1) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.HasLen(got, 2), qt.Commentf("before its end")) + + time.Sleep(1300 * time.Millisecond) + got, err = s.Connections(ctx, tenantA, assistant1) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.DeepEquals(ids(got), []string{"public-long=sid-long"}), qt.Commentf("after its end")) + + err = s.AddConnection(ctx, tenantA, assistant1, session.Connection{ID: "p", SessionID: "s"}, time.Now().Add(-time.Second)) + notFound(t, err) + }) +} + +// The in-memory store, on its own clock: a connection ending at t is listed a +// moment before t and not at t, as a session ends when now is not before its end. +func TestTheMemoryStoreEndsAConnectionAtItsEnd(t *testing.T) { + m := sessiontest.NewMemory() + start := time.Date(2026, 11, 5, 9, 0, 0, 0, time.UTC) + m.SetClock(func() time.Time { return start }) + ctx := context.Background() + end := start.Add(time.Hour) + qt.Assert(t, qt.IsNil(m.AddConnection(ctx, tenantA, assistant1, session.Connection{ID: "p", SessionID: "s"}, end))) + + m.SetClock(func() time.Time { return end.Add(-time.Millisecond) }) + got, err := m.Connections(ctx, tenantA, assistant1) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.HasLen(got, 1)) + + m.SetClock(func() time.Time { return end }) + got, err = m.Connections(ctx, tenantA, assistant1) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.HasLen(got, 0)) +} diff --git a/session/session.go b/session/session.go index 1389a0f..cf8104c 100644 --- a/session/session.go +++ b/session/session.go @@ -156,6 +156,20 @@ type Session struct { // the boxes the app asked for. Both are re-checked at every refresh. Assistant string `json:"assistant,omitempty"` AppScopes []string `json:"app_scopes,omitempty"` + // ConnectedAt is, for an AI app's connection, when the app redeemed its code + // and so first held its tokens; LastUsed when a call through it last reached + // this service (the exchange a tool call makes), zero until the first. Its SID + // is the connection's public name: the person and an administrator sign it out + // by it, and the app's tokens name it. + ConnectedAt time.Time `json:"connected_at,omitzero"` + LastUsed time.Time `json:"last_used,omitzero"` +} + +// Connection is one AI app's connection as an assistant's index keeps it: its +// public name and the key of its session, which never leaves this service. +type Connection struct { + ID string + SessionID string } // Expired reports whether the session's lifetime has run out at now. A session diff --git a/session/sessiontest/memory.go b/session/sessiontest/memory.go index a4c55ce..59f5c10 100644 --- a/session/sessiontest/memory.go +++ b/session/sessiontest/memory.go @@ -345,4 +345,76 @@ func (m *Memory) EndShared(_ context.Context, id string) (map[string]string, err return apps, nil } +// connections is an index as the real store keeps it: each connection by its +// public name and session key, with its end in Unix milliseconds. +func (m *Memory) connections(tenant, assistant string) (string, map[string]int64) { + key := "conn:" + tenant + "/" + assistant + index := map[string]int64{} + if e, ok := m.entries[key]; ok && m.live(e) { + _ = json.Unmarshal(e.value, &index) + } + + return key, index +} + +func (m *Memory) AddConnection(_ context.Context, tenant, assistant string, c session.Connection, until time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + + if !m.now().Before(until) { + return session.ErrNotFound + } + + key, index := m.connections(tenant, assistant) + index[c.ID+" "+c.SessionID] = until.UnixMilli() + b, err := json.Marshal(index) + if err != nil { + return err + } + e := entry{value: b, expires: until} + if old, ok := m.entries[key]; ok && m.live(old) && old.expires.After(until) { + e.expires = old.expires + } + m.entries[key] = e + + return nil +} + +func (m *Memory) Connections(_ context.Context, tenant, assistant string) ([]session.Connection, error) { + m.mu.Lock() + defer m.mu.Unlock() + + _, index := m.connections(tenant, assistant) + now := m.now().UnixMilli() + var out []session.Connection + for k, end := range index { + if end <= now { + continue + } + if id, sid, ok := strings.Cut(k, " "); ok { + out = append(out, session.Connection{ID: id, SessionID: sid}) + } + } + + return out, nil +} + +func (m *Memory) RemoveConnection(_ context.Context, tenant, assistant string, c session.Connection) error { + m.mu.Lock() + defer m.mu.Unlock() + + key, index := m.connections(tenant, assistant) + if _, ok := index[c.ID+" "+c.SessionID]; !ok { + return nil + } + delete(index, c.ID+" "+c.SessionID) + b, err := json.Marshal(index) + if err != nil { + return err + } + m.entries[key] = entry{value: b, expires: m.entries[key].expires} + + return nil +} + func (m *Memory) Ping(context.Context) error { return nil } diff --git a/session/store.go b/session/store.go index 7d98a3d..c7ad3a5 100644 --- a/session/store.go +++ b/session/store.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "strconv" + "strings" "time" "azugo.io/core/cache" @@ -23,8 +24,24 @@ const ( // the app sessions signed in under each: a hash of client id to session id. sharedInstance = "shared" sharedAppsInstance = "shared-apps" + // connectionsInstance keeps each assistant's index of AI apps connected as it, + // per workspace: a sorted set of connections scored by their end. + connectionsInstance = "connections" ) +// addConnection adds a connection to an index, scored by its end, and keeps the +// index at least that long, so an index outlives none of its live connections. +const addConnection = `redis.call('ZADD', KEYS[1], ARGV[1], ARGV[2]) +local t = redis.call('PTTL', KEYS[1]) +if t < tonumber(ARGV[3]) then redis.call('PEXPIRE', KEYS[1], ARGV[3]) end +return 1` + +// liveConnections drops an index's connections whose end has come (now at their +// end included, as a session ends when now is not before its end) and answers +// the rest, in one step. +const liveConnections = `redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1]) +return redis.call('ZRANGE', KEYS[1], 0, -1)` + // putSharedApp records an app session under a shared session in one step, // answering the session the same client had there before ("" when none), so two // sign-ins at once neither lose a client nor leave an earlier session unnamed. @@ -368,6 +385,68 @@ func (s *Store) EndShared(ctx context.Context, id string) (map[string]string, er return con.Do(ctx, cmd).AsStrMap() } +// connectionKey is the index key of an assistant's connections in a workspace. +func (s *Store) connectionKey(tenant, assistant string) string { + return s.key(connectionsInstance, tenant+"/"+assistant) +} + +// member is how the index names a connection: its public name and its session's +// key, neither of which holds a space. +func member(c Connection) string { return c.ID + " " + c.SessionID } + +// AddConnection keeps c in its assistant's index until until. +func (s *Store) AddConnection(ctx context.Context, tenant, assistant string, c Connection, until time.Time) error { + left := until.Sub(s.now()) + if left <= 0 { + return ErrNotFound + } + + con := s.cache.Connection() + if con == nil { + return cache.ErrCacheUnavailable + } + + cmd := con.B().Eval().Script(addConnection).Numkeys(1).Key(s.connectionKey(tenant, assistant)). + Arg(strconv.FormatInt(until.UnixMilli(), 10), member(c), strconv.FormatInt(left.Milliseconds(), 10)).Build() + + return con.Do(ctx, cmd).Error() +} + +// Connections answers the live connections in an assistant's index, dropping +// those whose end has come. +func (s *Store) Connections(ctx context.Context, tenant, assistant string) ([]Connection, error) { + con := s.cache.Connection() + if con == nil { + return nil, cache.ErrCacheUnavailable + } + + cmd := con.B().Eval().Script(liveConnections).Numkeys(1).Key(s.connectionKey(tenant, assistant)). + Arg(strconv.FormatInt(s.now().UnixMilli(), 10)).Build() + members, err := con.Do(ctx, cmd).AsStrSlice() + if err != nil { + return nil, err + } + + out := make([]Connection, 0, len(members)) + for _, m := range members { + if id, sid, ok := strings.Cut(m, " "); ok { + out = append(out, Connection{ID: id, SessionID: sid}) + } + } + + return out, nil +} + +// RemoveConnection takes c out of its assistant's index. +func (s *Store) RemoveConnection(ctx context.Context, tenant, assistant string, c Connection) error { + con := s.cache.Connection() + if con == nil { + return cache.ErrCacheUnavailable + } + + return con.Do(ctx, con.B().Zrem().Key(s.connectionKey(tenant, assistant)).Member(member(c)).Build()).Error() +} + // Ping verifies the cache can be reached. func (s *Store) Ping(ctx context.Context) error { if err := s.cache.Ping(ctx); err != nil { diff --git a/signin_token_test.go b/signin_token_test.go index 7712724..5520763 100644 --- a/signin_token_test.go +++ b/signin_token_test.go @@ -19,7 +19,7 @@ func TestTheSignInDoorTokenIsShortAndBound(t *testing.T) { tok, err := app.mintSignInToken("01K9ANNA0000000000000000AA", "svc:rolebyte", "membership:resolve", "svc:authbyte-core", "the-outbound-key") qt.Assert(t, qt.IsNil(err)) - c, err := app.Issuer().ParseSubjectToken(tok) + c, _, err := app.Issuer().ParseSubjectToken(tok) qt.Assert(t, qt.IsNil(err)) qt.Check(t, qt.IsTrue(c.ExpiresAt.Sub(c.IssuedAt.Time) <= signInTokenTTL)) qt.Check(t, qt.Equals(signInTokenTTL, time.Minute))