From 914b264632374ef24d25b0bc5a23da6bedccd9b3 Mon Sep 17 00:00:00 2001 From: GatisB Date: Wed, 11 Nov 2026 13:09:09 +0000 Subject: [PATCH 1/6] Build on Go 1.27.4 Signed-off-by: GatisB --- Dockerfile | 2 +- go.mod | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index ad2070d..b0da096 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -ARG GO_VERSION=1.27.3 +ARG GO_VERSION=1.27.4 FROM golang:${GO_VERSION} AS build WORKDIR /src diff --git a/go.mod b/go.mod index aef069f..2d1ad4c 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/go-make-bytes/authbyte -go 1.27.3 +go 1.27.4 require ( azugo.io/azugo v0.40.2 From 9ccd0a59395a85a2a2851107fd6bb727fc976584 Mon Sep 17 00:00:00 2001 From: GatisB Date: Wed, 11 Nov 2026 13:09:12 +0000 Subject: [PATCH 2/6] Scopes that count only on a high sign-in: read from the membership register, given to a sign-in client set to carry them, never by a registry grant; scopes of no valid shape are left out of a token Signed-off-by: GatisB --- CHANGELOG.md | 31 +++++ README.md | 19 ++- SECURITY.md | 2 + registry/registry.go | 58 ++++++++- registry/reserved_test.go | 140 +++++++++++++++++++++ rolebyte/rolebyte.go | 15 ++- rolebyte/rolebyte_test.go | 34 +++++ routes/token.go | 70 ++++++++++- routes/token_highscopes_test.go | 214 ++++++++++++++++++++++++++++++++ routes/token_rolebyte_test.go | 12 ++ 10 files changed, 585 insertions(+), 10 deletions(-) create mode 100644 registry/reserved_test.go create mode 100644 routes/token_highscopes_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dac175..3b14a13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,37 @@ Notable changes to this service, newest first, per release. This file is written for whoever runs the service or integrates against it. +## v0.13.0 + +### Added + +- **A person's token can carry scopes that count only on a high sign-in.** Each membership the register answers may now + list `highScopes` beside `scopes`. A person's token carries them, after the membership's own scopes and without + repeating one, only when the session's assurance level is `high` **and** the sign-in client the token is issued to + says `high_scopes: true`, a new setting that is off by default; at any other level, with the setting off, or when + the level is unknown, they are left out. They are decided again at every refresh from the register's current + answer and the level the session holds, so a scope the register stops answering leaves with the next refresh. A + service account's tenant token, an AI app's token and a client that needs no membership never carry them; a + sign-in client that needs no membership, or an AI app, that says `high_scopes` stops the start. The log line that + reports what the register answered now also lists each membership's high-only scopes. This needs nothing from the + register: an older register sends no such list and nothing changes. +- **The scope group `deployment` is reserved to the register.** A client registry document that names a + `deployment:` scope in a grant's `scopes`, in a grant's `assistant_levels` or in a sign-in client's + `baseline_scopes` stops the start, naming the client and the scope. A baseline scope must now be a box or a level, + as a grant's scope already had to be. +- **A scope the register answers that is neither a box nor a level is left out of a token.** A token's scopes are one + string split on white space where it is read, so a scope holding white space, a no-break space included, would be + read as two. It is dropped, with one warning naming the tenant and the count, and the issue goes on with the + others; this holds a service account's tenant token too. + +**Deploy:** a deployment that wants its admin application's people to receive the scopes that count only on a high +sign-in sets `high_scopes: true` on that sign-in client in the registry document. Nothing changes for a deployment that +does not. A registry that names a `deployment:` scope, or a baseline scope of no shape, now stops the start. + +### Changed + +- **Built and run on Go 1.27.4.** + ## v0.12.0 ### Added diff --git a/README.md b/README.md index 80c24fc..5982cae 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,15 @@ ship separately, so this boundary is a published contract: (`kind: sign-in`), which a healthy deployment never produces. - **Answer:** the subject's active memberships — each organisation with the `group:level` scopes the subject's roles grant there. The register attaches any pending invitation first, - so a subject's very first token already carries the invited roles. + so a subject's very first token already carries the invited roles. The register may also mark, + per membership, `highScopes`: scopes that are given only when the person signed in at the high + assurance level. They are added after the membership's own scopes, at the sign-in and re-read at + every refresh, only when the session's level is `high` **and** the client the token is issued to + says `high_scopes: true` (off by default); they never reach a service account's, an AI app's + or a baseline-scopes token, and a register that sends none changes nothing. Any scope the register + answers that is neither a box nor a level (one holding white space, say) is left out of the token + with one warning naming the tenant and the count, and the issue goes on; this holds a service + account's tenant token too. - **The admission door, for a login through an organisation's own directory.** Such a session carries the issuer it came through. When the person has just signed in and holds no membership, this service offers them to the register's admission door (`POST /api/v1/sign-in/directory-admissions`, the @@ -562,7 +570,7 @@ can be stated alongside the country. | `OIDC_UPSTREAM_METHODS_FEDERATED` | — (none) | Comma-separated methods whose sign-out also goes through the provider's end-session endpoint, ending the session it keeps in the browser. Unset, signing out ends this service's session and leaves the provider's alone — a directory provider's session is the person's whole estate. The eParaksts profile lists its own methods regardless | | `OIDC_UPSTREAM_LOA_DEFAULT` | `low` | Assurance level when no `LOA_POLICY` token matches — raise deliberately for an IdP that enforces MFA | | `OIDC_UPSTREAM_DISPLAY_NAME` | — (⇒ "Your organisation's sign-in", in the page's language) | The generic provider's name on the sign-in page's button, e.g. `Microsoft Entra` | -| `LOA_POLICY` | — (⇒ built-in: the eParaksts profile's level and method words; another provider's explicit `level:*` words only, then `OIDC_UPSTREAM_LOA_DEFAULT`) | Override the `acr`/`amr` → assurance-level vocabulary (`substr=loa,…`; longest token wins, equal lengths in alphabetical order) | +| `LOA_POLICY` | — (⇒ built-in: the eParaksts profile's level and method words; another provider's explicit `level:*` words only, then `OIDC_UPSTREAM_LOA_DEFAULT`) | Override the `acr`/`amr` → assurance-level vocabulary (`substr=loa,…`; longest token wins, equal lengths in alphabetical order). A deployment that makes a sign-in way count as `high` here or through `OIDC_UPSTREAM_LOA_DEFAULT` also gives the people who sign in that way the scopes that count only on a high sign-in, where their client says `high_scopes: true` | | Env (eParaksts profile) | Default | Meaning | |---|---|---| @@ -629,7 +637,11 @@ proves itself with its secret and is minted tokens for the audiences and scopes allow (`act_from` names the user audiences whose tokens it may exchange). A grant's scope is a box (`service/feature:act`) or a level (`group:level`), and anything else stops the start; a grant's `assistant_levels` names those of its levels that may ride a token made through a person's assistant -(empty by default, each one a level of the grant). `sign_in_clients` sign +(empty by default, each one a level of the grant). **The scope group `deployment` is reserved:** every +`deployment:` scope is given only by the membership register, as a scope that counts only on a high sign-in, +so a grant's `scopes`, a grant's `assistant_levels` and a sign-in client's `baseline_scopes` that name one stop the +start, the client and the scope named; a baseline scope, like a grant's, must also be a box or a level. +`sign_in_clients` sign people in, and each row carries everything its product needs, so one deployment serves several products. The names follow the client metadata of [RFC 7591 §2] and the OpenID logout specifications where one exists: @@ -643,6 +655,7 @@ sign_in_clients: audience: portal-api # the aud of this client's user tokens membership_required: false # see "Supported configurations" baseline_scopes: [envelopes:read, documents:read] # only where no membership is asked + high_scopes: false # true: its people's tokens may carry the register's high-only scopes (off by default; only where a membership is asked) claims: [name, given_name, family_name, serial_number] # the personal claims its tokens carry methods: [eparakstsMobile, eidScan, webEid] # the sign-in methods it allows signing: true # told the signing flows; its sign-ins capture signing identities diff --git a/SECURITY.md b/SECURITY.md index 8cc00f0..8d0f8dd 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -42,6 +42,8 @@ supposed to prove: - forging, replaying or unbinding sender-constrained (DPoP) tokens or delegated (exchange) tokens; - influencing the token-signing key, the JWKS, or the client registry; - bypassing the login-method / level-of-assurance binding that signing flows rely on; +- giving a person a scope that counts only on a high sign-in at a lower level, or through a client not set to carry it, + or handing out a scope of the reserved `deployment` group from the client registry; - weakening or bypassing the audit records that are meant to be evidence. Denial of service and findings that need an already-compromised host or an already-authenticated diff --git a/registry/registry.go b/registry/registry.go index dc7052b..d79d719 100644 --- a/registry/registry.go +++ b/registry/registry.go @@ -54,6 +54,33 @@ const ( var knownClaims = []string{ClaimName, ClaimGivenName, ClaimFamilyName, ClaimSerialNumber} +// ReservedScopeGroup is the scope group the membership register alone gives out: +// every `deployment:` scope is answered by the register, as a scope that +// counts only on a high sign-in. No registry entry may name one, so the document +// can never hand it to a client, an assistant or a person's baseline. +const ReservedScopeGroup = "deployment" + +// InReservedGroup reports whether a scope belongs to [ReservedScopeGroup]: its +// group, the part before the first colon, is exactly that name. +func InReservedGroup(s string) bool { + group, _, ok := strings.Cut(s, ":") + + return ok && group == ReservedScopeGroup +} + +// checkNotReserved refuses a registry scope list that holds a scope of the +// reserved group; what names the list in the error ("grant to ..."). +func checkNotReserved(owner, what string, scopes []string) error { + for _, s := range scopes { + if InReservedGroup(s) { + return fmt.Errorf("registry: %s: %s %q is in the %q scope group, which only the membership register gives out", + owner, what, s, ReservedScopeGroup) + } + } + + return nil +} + // Grant is a single audience the client may target and the scopes it may // request toward it. type Grant struct { @@ -112,6 +139,11 @@ type SignInClient struct { // BaselineScopes are what a person signing in through this client is minted // when no membership is consulted. BaselineScopes []string `yaml:"baseline_scopes"` + // HighScopes says whether the tokens of the people who sign in through this + // client may carry the scopes the register marks as counting only on a high + // sign-in. Off unless set; even then they are added only when the session's + // assurance level is high. + HighScopes bool `yaml:"high_scopes"` // Claims are the personal claims its tokens carry, from the known four; the // identity code (serial_number) only where it is listed. Claims []string `yaml:"claims"` @@ -259,12 +291,19 @@ func validateClient(c Client) error { if slices.ContainsFunc(c.Grants[:i], func(o Grant) bool { return o.Audience == g.Audience }) { return fmt.Errorf("registry: client %q has two grants to %q", c.ClientID, g.Audience) } + owner := fmt.Sprintf("client %q grant to %q", c.ClientID, g.Audience) for _, s := range g.Scopes { if !IsBox(s) && !IsLevel(s) { return fmt.Errorf("registry: client %q grant to %q: scope %q is neither a box (service/feature:act) nor a level (group:level)", c.ClientID, g.Audience, s) } } + if err := checkNotReserved(owner, "scope", g.Scopes); err != nil { + return err + } + if err := checkNotReserved(owner, "assistant_levels", g.AssistantLevels); err != nil { + return err + } for _, s := range g.AssistantLevels { if !IsLevel(s) { return fmt.Errorf("registry: client %q grant to %q: assistant_levels %q is not a level (group:level)", @@ -315,6 +354,21 @@ func validateSignInClient(c SignInClient) error { if len(c.BaselineScopes) > 0 && c.MembershipRequired != nil && *c.MembershipRequired { return bad("requires a membership, so its baseline_scopes could never apply") } + // A baseline scope is a box or a level, as a grant's scope is, and never one + // of the reserved group: those come only from the register. + for _, s := range c.BaselineScopes { + if !IsBox(s) && !IsLevel(s) { + return bad("baseline_scopes %q is neither a box (service/feature:act) nor a level (group:level)", s) + } + } + if err := checkNotReserved(fmt.Sprintf("sign-in client %q", c.ClientID), "baseline_scopes", c.BaselineScopes); err != nil { + return err + } + // The scopes that count only on a high sign-in come from the register's + // answer, which a client with no membership asked never has. + if c.HighScopes && c.MembershipRequired != nil && !*c.MembershipRequired { + return bad("does not ask the register about its people, so high_scopes could never apply") + } // A signing session's identities are read from the provider at a sign-in; an // answer from the shared session has no provider to read them from. if c.Signing && c.SingleSignOn { @@ -372,9 +426,9 @@ func validateAIApp(c SignInClient, bad func(string, ...any) error) error { if c.Type != ClientPublic { return bad("is an %s, which is a public client", KindAIApp) } - if len(c.Claims) > 0 || c.Signing || c.SingleSignOn || len(c.BaselineScopes) > 0 || + if len(c.Claims) > 0 || c.Signing || c.SingleSignOn || len(c.BaselineScopes) > 0 || c.HighScopes || (c.MembershipRequired != nil && !*c.MembershipRequired) { - return bad("is an %s: it takes no claims, signing, single_sign_on, baseline_scopes or a sign-in without a membership", KindAIApp) + return bad("is an %s: it takes no claims, signing, single_sign_on, baseline_scopes, high_scopes or a sign-in without a membership", KindAIApp) } if err := checkResource(c.Audience); err != nil { return bad("audience %q is not a resource: %w", c.Audience, err) diff --git a/registry/reserved_test.go b/registry/reserved_test.go new file mode 100644 index 0000000..5fcdfe3 --- /dev/null +++ b/registry/reserved_test.go @@ -0,0 +1,140 @@ +package registry + +import ( + "fmt" + "strings" + "testing" +) + +// signInWith is one sign-in client with the given extra lines. +func signInWith(extra string) string { + return ` +sign_in_clients: + - client_id: admin-app + enabled: true + type: public + audience: admin-portal + redirect_uris: [https://admin.example/callback] +` + extra +} + +// The scope group the register alone gives out can be named by no registry +// entry: not a grant's scopes, not its assistant_levels, not a baseline. +func TestLoadRefusesAScopeOfTheReservedGroup(t *testing.T) { + for name, tc := range map[string]struct { + doc string + want []string + }{ + "a grant's scopes": { + grantDoc("[membership:people, deployment:admin]", ""), + []string{`"svc:product-api"`, `"svc:register"`, `"deployment:admin"`}, + }, + "a grant's scopes, another level of the group": { + grantDoc("[deployment:read]", ""), + []string{`"svc:product-api"`, `"deployment:read"`}, + }, + "a grant's assistant_levels": { + grantDoc("[membership:people]", "[deployment:admin]"), + []string{`"svc:product-api"`, `"deployment:admin"`}, + }, + "a sign-in client's baseline": { + signInWith(" membership_required: false\n baseline_scopes: [records:read, deployment:admin]\n"), + []string{`"admin-app"`, `"deployment:admin"`}, + }, + "a sign-in client's baseline, another level": { + signInWith(" membership_required: false\n baseline_scopes: [deployment:read]\n"), + []string{`"admin-app"`, `"deployment:read"`}, + }, + } { + t.Run(name, func(t *testing.T) { + _, err := Load([]byte(tc.doc), nil) + if err == nil { + t.Fatal("the registry loaded") + } + for _, want := range tc.want { + if !strings.Contains(err.Error(), want) { + t.Errorf("the error %q does not name %s", err, want) + } + } + }) + } +} + +// The same documents with another group load, and a name that only starts like +// the reserved group is not in it. +func TestLoadAcceptsTheSameShapesOfAnotherGroup(t *testing.T) { + for name, doc := range map[string]string{ + "a grant's scopes": grantDoc("[membership:people, workspace:admin]", ""), + "a grant's assistant_levels": grantDoc("[workspace:admin]", "[workspace:admin]"), + "a baseline": signInWith(" membership_required: false\n baseline_scopes: [workspace:admin]\n"), + "a longer group name": grantDoc("[deployments:admin, deployment-x:admin]", ""), + "a box of that service": grantDoc("[deployment/feature:view]", ""), + } { + t.Run(name, func(t *testing.T) { + if _, err := Load([]byte(doc), nil); err != nil { + t.Fatalf("Load: %v", err) + } + }) + } +} + +// A baseline scope is a box or a level, like a grant's, or the start stops with +// the client and the scope named. +func TestLoadRefusesABaselineScopeOfNoShape(t *testing.T) { + for _, scope := range []string{"admin", "a:b:c", "a:b c:d", "a:b c:d", ":read", "projects/task:"} { + _, err := Load([]byte(signInWith(" membership_required: false\n baseline_scopes: ['"+scope+"']\n")), nil) + if err == nil { + t.Errorf("the baseline scope %q loaded", scope) + + continue + } + for _, want := range []string{`"admin-app"`, fmt.Sprintf("%q", scope)} { + if !strings.Contains(err.Error(), want) { + t.Errorf("%q: the error %q does not name %s", scope, err, want) + } + } + } +} + +// high_scopes is off unless set, and meaningless where the register is not asked. +func TestHighScopesSettingOffByDefaultAndRefusedWhereItCouldNotApply(t *testing.T) { + r, err := Load([]byte(signInWith(" high_scopes: true\n")), nil) + if err != nil { + t.Fatalf("Load: %v", err) + } + if c, _ := r.SignInClient("admin-app"); !c.HighScopes { + t.Error("high_scopes: true was not kept") + } + + r, err = Load([]byte(signInWith("")), nil) + if err != nil { + t.Fatalf("Load: %v", err) + } + if c, _ := r.SignInClient("admin-app"); c.HighScopes { + t.Error("high_scopes is on without being set") + } + + _, err = Load([]byte(signInWith(" membership_required: false\n high_scopes: true\n")), nil) + if err == nil || !strings.Contains(err.Error(), "high_scopes") || !strings.Contains(err.Error(), `"admin-app"`) { + t.Errorf("a client that asks no membership took high_scopes: %v", err) + } +} + +// White space outside ASCII is white space: a scope holding any of these is +// neither a box nor a level, so it cannot be split into two where it is read. +func TestShapeTestsCatchNonASCIISpace(t *testing.T) { + for name, sp := range map[string]string{ + "U+00A0 no-break space": " ", + "U+0085 next line": "\u0085", + "U+2007 figure space": " ", + "U+202F narrow no-break space": " ", + "ASCII space": " ", + } { + if IsLevel("a:b" + sp + "c") { + t.Errorf("%s: IsLevel accepted a scope holding it", name) + } + if IsBox("a/b:c" + sp + "d") { + t.Errorf("%s: IsBox accepted a scope holding it", name) + } + } +} diff --git a/rolebyte/rolebyte.go b/rolebyte/rolebyte.go index 774c9e6..16d9e4f 100644 --- a/rolebyte/rolebyte.go +++ b/rolebyte/rolebyte.go @@ -78,9 +78,14 @@ type Minter func(subject, audience, scope, actor, thumbprint string) (string, er // Membership is one organisation a subject may act under, with the // group:level scopes its roles grant there. +// +// HighScopes are scopes that count only when the person signed in at the highest +// assurance level; the caller decides, from the session's level, whether they +// are added. An older register sends none, and the list is then empty. type Membership struct { - TenantID string - Scopes []string + TenantID string + Scopes []string + HighScopes []string } // Resolver answers membership questions from the register. @@ -184,6 +189,10 @@ func (r *Resolver) Admit(ctx *azugo.Context, subjectKey string, login DirectoryL type membership struct { TenantID string `json:"tenantId"` Scopes []string `json:"scopes"` + // HighScopes are the scopes that count only on a high-assurance sign-in. + // Absent, null or empty all decode to no scopes: a register that does not + // send the member changes nothing. + HighScopes []string `json:"highScopes"` } type resolveResponse struct { @@ -287,7 +296,7 @@ func (r *Resolver) Memberships(ctx *azugo.Context, subjectKey string) ([]Members // after it. tenants := make([]string, 0, len(res.Memberships)) for _, m := range res.Memberships { - tenants = append(tenants, m.TenantID+"="+strings.Join(m.Scopes, ",")) + tenants = append(tenants, m.TenantID+"="+strings.Join(m.Scopes, ",")+" high-only="+strings.Join(m.HighScopes, ",")) } ctx.Log().Info("membership resolved", zap.String("asked", subjectKey), zap.String("answered_for", res.SubjectKey), zap.Strings("memberships", tenants)) diff --git a/rolebyte/rolebyte_test.go b/rolebyte/rolebyte_test.go index 2361c37..56e957d 100644 --- a/rolebyte/rolebyte_test.go +++ b/rolebyte/rolebyte_test.go @@ -253,3 +253,37 @@ func TestAdmitSendsOnlyWhatTheLoginKnows(t *testing.T) { qt.Assert(t, qt.IsNil(json.Unmarshal([]byte(reg.calls[0].body), &body))) qt.Check(t, qt.DeepEquals(body, map[string]string{"issuer": "https://login.example/t", "displayName": "Anna"})) } + +// The high-only list is read leniently: present, absent (an older register), +// null and empty all decode, and only a present, non-empty list holds scopes. +func TestMembershipsDecodeTheHighOnlyScopes(t *testing.T) { + for name, tc := range map[string]struct { + member string + want []string + }{ + "present": {`"highScopes":["deployment:admin"],`, []string{"deployment:admin"}}, + "absent": {``, nil}, + "null": {`"highScopes":null,`, nil}, + "empty": {`"highScopes":[],`, []string{}}, + } { + t.Run(name, func(t *testing.T) { + reg := newSignInRegister(t, map[string]func(w http.ResponseWriter){ + doorClaims: answerJSON(`{"claimed":[]}`), + doorMemberships: answerJSON(`{"subjectKey":"sub:` + annaSub + `","memberships":[{"tenantId":"t1",` + + tc.member + `"scopes":["a:b"]}]}`), + }) + r, _ := reg.resolver() + + inRequest(t, func(ctx *azugo.Context) { + got, err := r.Memberships(ctx, PersonKey(annaSub)) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.HasLen(got, 1)) + qt.Check(t, qt.DeepEquals(got[0].Scopes, []string{"a:b"})) + qt.Check(t, qt.HasLen(got[0].HighScopes, len(tc.want))) + if len(tc.want) > 0 { + qt.Check(t, qt.DeepEquals(got[0].HighScopes, tc.want)) + } + }) + }) + } +} diff --git a/routes/token.go b/routes/token.go index 7038e85..0e2008e 100644 --- a/routes/token.go +++ b/routes/token.go @@ -16,6 +16,7 @@ import ( "azugo.io/azugo" corehttp "azugo.io/core/http" "github.com/valyala/fasthttp" + "go.uber.org/zap" ) // issueMoment is why a user token is being issued: a sign-in, where an @@ -106,7 +107,69 @@ func (r *router) userScopes(ctx *azugo.Context, sess *session.Session, clientID, return membershipOutcome{choices: choices}, true } - return membershipOutcome{scopes: chosen.Scopes, tenant: chosen.TenantID}, true + // The scopes that count only on a high sign-in go to a client that is set to + // carry them, never to one that is not. + client, _ := r.Registry().SignInClient(clientID) + scopes, dropped := withHighScopes(chosen, sess.LoA, client.HighScopes) + warnDroppedScopes(ctx, chosen.TenantID, dropped) + + return membershipOutcome{scopes: scopes, tenant: chosen.TenantID}, true +} + +// withHighScopes answers the scopes a person's token carries from the chosen +// membership: its scopes, and — only when the session's assurance level is +// exactly high and the client the token is issued to is set to carry them +// (highAllowed) — its high-only scopes after them, skipping any already present. +// Any other level, including an empty or unknown one, adds nothing. The level is +// the one the session holds at this issue, so every refresh decides again from +// the register's current answer. Each scope is held to a shape first; dropped +// counts those left out. +func withHighScopes(m *rolebyte.Membership, loa string, highAllowed bool) (scopes []string, dropped int) { + scopes, dropped = shapedScopes(m.Scopes) + if loa != identity.LoAHigh || !highAllowed || len(m.HighScopes) == 0 { + return scopes, dropped + } + + high, n := shapedScopes(m.HighScopes) + for _, s := range high { + if !slices.Contains(scopes, s) { + scopes = append(scopes, s) + } + } + + return scopes, dropped + n +} + +// shapedScopes keeps the scopes that are a box or a level and counts the rest. +// A token's scopes are one string split on white space where it is read, so a +// scope that held white space — a no-break space as well as an ASCII one — would +// be read as two; the register's answer is held to the same shape as a registry +// document before anything is minted from it. +func shapedScopes(in []string) (kept []string, dropped int) { + if in != nil { + kept = make([]string, 0, len(in)) // an empty list stays empty, not absent + } + for _, s := range in { + if !registry.IsBox(s) && !registry.IsLevel(s) { + dropped++ + + continue + } + kept = append(kept, s) + } + + return kept, dropped +} + +// warnDroppedScopes logs, once, that the register answered scopes of no valid +// shape for a tenant. It names the tenant and the count, never the scopes. +func warnDroppedScopes(ctx *azugo.Context, tenant string, dropped int) { + if dropped == 0 { + return + } + + ctx.Log().Warn("the register answered scopes that are neither a box nor a level; left out of the token", + zap.String("tenant", tenant), zap.Int("dropped", dropped)) } // registerUnavailable fails a token issue closed when the register is @@ -535,7 +598,10 @@ func (r *router) serviceAccountScopes(ctx *azugo.Context, clientID, tenant strin return nil, err } - scopes := intersectScopes(allowed, chosen.Scopes) + granted, dropped := shapedScopes(chosen.Scopes) + warnDroppedScopes(ctx, chosen.TenantID, dropped) + + scopes := intersectScopes(allowed, granted) if len(scopes) == 0 { // A member, but with no role toward this audience: nothing to mint. err := corehttp.ForbiddenError{} diff --git a/routes/token_highscopes_test.go b/routes/token_highscopes_test.go new file mode 100644 index 0000000..97ff5ae --- /dev/null +++ b/routes/token_highscopes_test.go @@ -0,0 +1,214 @@ +package routes + +import ( + "encoding/json" + "testing" + + "github.com/go-make-bytes/authbyte/identity" + "github.com/go-make-bytes/authbyte/rolebyte" + + "github.com/go-quicktest/qt" + "github.com/valyala/fasthttp" +) + +const highOnly = "deployment:admin" + +// withHigh is a membership whose roles grant scopes and whose register marks +// highScopes as counting only on a high sign-in. +func withHigh(tenant string, scopes, high []string) rolebyte.Membership { + return rolebyte.Membership{TenantID: tenant, Scopes: scopes, HighScopes: high} +} + +type scopesAnswer struct { + Scopes []string `json:"scopes"` +} + +func decodeScopes(t *testing.T, body string) []string { + t.Helper() + + var a scopesAnswer + qt.Assert(t, qt.IsNil(json.Unmarshal([]byte(body), &a)), qt.Commentf("%s", body)) + + return a.Scopes +} + +// The high-only scopes join the token only when the session's level is exactly +// high; low, substantial, an empty level and an unknown one add nothing. +func TestUserScopesHighScopesOnlyAtTheHighLevel(t *testing.T) { + for name, tc := range map[string]struct { + loa string + want []string + }{ + "high": {identity.LoAHigh, []string{"a:b", highOnly}}, + "substantial": {identity.LoASubstantial, []string{"a:b"}}, + "low": {identity.LoALow, []string{"a:b"}}, + "empty": {"", []string{"a:b"}}, + "unknown": {"HIGH", []string{"a:b"}}, + } { + t.Run(name, func(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{withHigh("01TENANTA", []string{"a:b"}, []string{highOnly})}} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/scopes?client=admin-spa&loa="+tc.loa) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), tc.want)) + }) + } +} + +// A register that sends no highScopes member (an older register) gives only +// the scopes, at every level. +func TestUserScopesWithoutHighScopesAtEveryLevel(t *testing.T) { + for _, loa := range []string{identity.LoAHigh, identity.LoASubstantial, identity.LoALow, "", "other"} { + fake := &fakeResolver{memberships: []rolebyte.Membership{member("01TENANTA", "a:b")}} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/scopes?client=product-spa&loa="+loa) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), []string{"a:b"}), qt.Commentf("level %q", loa)) + } +} + +// A high-only scope the membership already holds is not added twice, and the +// existing scopes keep their order. +func TestUserScopesHighScopesAreNotDuplicated(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + withHigh("01TENANTA", []string{"z:z", "a:b", highOnly}, []string{"a:b", highOnly, "x:y", "x:y"}), + }} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/scopes?client=admin-spa&loa="+identity.LoAHigh) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), []string{"z:z", "a:b", highOnly, "x:y"})) +} + +// With several memberships and a named organisation, only the chosen +// membership's high-only scopes are used. +func TestUserScopesOnlyTheChosenMembershipsHighScopes(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + withHigh("01TENANTA", []string{"a:b"}, []string{highOnly}), + withHigh("01TENANTB", []string{"c:d"}, []string{"other:high"}), + }} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/scopes?client=admin-spa&tenant=01TENANTB&loa="+identity.LoAHigh) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), []string{"c:d", "other:high"})) +} + +// A refresh decides again from the register's current answer and the level the +// session holds: a high session whose answer stops carrying the high-only +// scopes loses them, and a substantial session never gets them. +func TestUserScopesRefreshReadsHighScopesAgain(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{withHigh("01TENANTA", []string{"a:b"}, []string{highOnly})}} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/scopes?client=admin-spa&refresh=1&loa="+identity.LoAHigh) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), []string{"a:b", highOnly})) + + // A substantial session, while the register still answers the scope. + status, body = get(t, app, "/testonly/scopes?client=admin-spa&refresh=1&loa="+identity.LoASubstantial) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), []string{"a:b"})) + + // The register stops answering it: the high session's next token drops it. + fake.memberships = []rolebyte.Membership{member("01TENANTA", "a:b")} + status, body = get(t, app, "/testonly/scopes?client=admin-spa&refresh=1&loa="+identity.LoAHigh) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), []string{"a:b"})) +} + +// A client that needs no membership keeps its baseline, whatever the register +// would answer. +func TestUserScopesBaselineClientNeverGetsHighScopes(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{withHigh("01TENANTA", []string{"a:b"}, []string{highOnly})}} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/scopes?client=portal-spa&loa="+identity.LoAHigh) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), []string{"envelopes:read", "envelopes:write", "documents:read"})) +} + +// The scopes that count only on a high sign-in reach a token only when the +// session's level is high AND the client it is issued to is set to carry them, +// at the sign-in and at a refresh alike. +func TestUserScopesHighScopesNeedTheLevelAndTheClientSetting(t *testing.T) { + for _, moment := range []string{"", "&refresh=1"} { + for name, tc := range map[string]struct { + loa, client string + want []string + }{ + "high, setting on": {identity.LoAHigh, "admin-spa", []string{"a:b", highOnly}}, + "high, setting off": {identity.LoAHigh, "product-spa", []string{"a:b"}}, + "substantial, setting on": {identity.LoASubstantial, "admin-spa", []string{"a:b"}}, + "substantial, off": {identity.LoASubstantial, "product-spa", []string{"a:b"}}, + } { + t.Run(name+moment, func(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{withHigh("01TENANTA", []string{"a:b"}, []string{highOnly})}} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/scopes?client="+tc.client+moment+"&loa="+tc.loa) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), tc.want)) + }) + } + } +} + +// A scope the register answers that is neither a box nor a level is left out of +// the token, and the issue goes on with the good ones. A token's scopes are one +// string split on white space where it is read, so a scope holding white space, +// a no-break space included, would be read as two. +func TestUserScopesLeaveOutScopesOfNoShape(t *testing.T) { + bad := []string{"x deployment:admin", "x deployment:admin", "a:b:c", ""} + good := []string{"a:b", "projects/task:view"} + + t.Run("scopes", func(t *testing.T) { + scopes := append(append([]string{bad[0], bad[1]}, good[0]), append([]string{bad[2], bad[3]}, good[1])...) + fake := &fakeResolver{memberships: []rolebyte.Membership{{TenantID: "01TENANTA", Scopes: scopes}}} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/scopes?client=product-spa&loa="+identity.LoAHigh) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), good)) + }) + + t.Run("high scopes at high with the setting on", func(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + {TenantID: "01TENANTA", Scopes: []string{good[0]}, HighScopes: []string{bad[0], bad[1], highOnly, bad[2], bad[3]}}, + }} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/scopes?client=admin-spa&loa="+identity.LoAHigh) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), []string{good[0], highOnly})) + }) +} + +// The same filter holds a service account's tenant token: what the membership +// answers of no shape is never intersected into it. +func TestServiceAccountScopesLeaveOutScopesOfNoShape(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + member("01TENANTACME", "signing-requests:write", "x signing-requests:read", "a:b:c", ""), + }} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/service?tenant=01TENANTACME&allowed=signing-requests:write,a:b:c") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), []string{"signing-requests:write"})) +} + +// A service account's tenant token is the registry grant narrowed by the +// membership's scopes alone: the high-only scopes never reach it, even when the +// grant would allow the name. +func TestServiceAccountScopesNeverCarryHighScopes(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + withHigh("01TENANTACME", []string{"signing-requests:write"}, []string{highOnly}), + }} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/service?tenant=01TENANTACME&allowed=signing-requests:write,"+highOnly) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.DeepEquals(decodeScopes(t, body), []string{"signing-requests:write"})) +} diff --git a/routes/token_rolebyte_test.go b/routes/token_rolebyte_test.go index c691ad2..8460846 100644 --- a/routes/token_rolebyte_test.go +++ b/routes/token_rolebyte_test.go @@ -62,6 +62,14 @@ sign_in_clients: claims: [name, given_name, family_name] methods: [webEid] redirect_uris: [https://product.example/callback] + - client_id: admin-spa + type: public + audience: product-api + enabled: true + high_scopes: true + claims: [name, given_name, family_name] + methods: [webEid] + redirect_uris: [https://admin.example/callback] ` // fakeResolver drives the membership seams without a live register. @@ -152,6 +160,10 @@ func scopesApp(t *testing.T, resolver authbytecore.ScopeResolver, setup ...func( if n := ctx.Query.StringOptional("name"); n != nil { sess.Name = *n } + // The assurance level the session holds at this moment. + if l := ctx.Query.StringOptional("loa"); l != nil { + sess.LoA = *l + } client, tenant := "", "" if c := ctx.Query.StringOptional("client"); c != nil { client = *c From 221146bd4618c410d3770cb0604601e4be5aebe5 Mon Sep 17 00:00:00 2001 From: GatisB Date: Fri, 13 Nov 2026 21:23:38 +0000 Subject: [PATCH 3/6] Token answer: list a person's organisations with their names when they are in more than one Signed-off-by: GatisB --- CHANGELOG.md | 9 + README.md | 11 +- rolebyte/rolebyte.go | 11 +- rolebyte/rolebyte_test.go | 30 ++ routes/response/response.go | 13 + routes/token.go | 29 +- routes/token_memberships_test.go | 525 +++++++++++++++++++++++++++++++ 7 files changed, 622 insertions(+), 6 deletions(-) create mode 100644 routes/token_memberships_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b14a13..af0e137 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ runs the service or integrates against it. ### Added +- **The token answer of a person in several organisations lists them by name.** When the membership register + answers more than one membership for a person, the answer of the code exchange and of every refresh carries + `memberships`: one entry for each organisation, in the register's order, with `tenant` (its id) and `name`, whether + or not one was chosen. An organisation the register gives no name is listed with an empty `name`. This is additive: + a client that ignores unknown keys is unaffected, `tenants` is unchanged, and a person in one organisation gets the + answer they got before. A refused answer, a service account's token, an AI app's token and a client that needs no + membership never carry the list. The names come from the membership register, which must be on the release that + answers `tenantName`; with an older register every name is empty. Nothing about choosing an organisation changed, + and no log line, audit event or error gains a name. - **A person's token can carry scopes that count only on a high sign-in.** Each membership the register answers may now list `highScopes` beside `scopes`. A person's token carries them, after the membership's own scopes and without repeating one, only when the session's assurance level is `high` **and** the sign-in client the token is issued to diff --git a/README.md b/README.md index 5982cae..e7c77ec 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,13 @@ organisation they do not belong to is refused `403 err:membership:notMember`) an organisation's token is minted. The choice is remembered by the session, so a refresh re-resolves the same organisation — and a revoked membership still dies at the next refresh. +The token response of a person in several organisations also lists them in **`memberships`**: one +entry for each, in the register's order, with the organisation's `tenant` (its id) and its `name` +(empty when the register holds none), so a client can show the choice by name. It is answered at the +code exchange and at every refresh, whether or not an organisation was chosen, from the register's +answer of that moment. `tenants` is unchanged. A person in one organisation gets neither key, and +a refused answer, a service account's token and an AI app's token never carry the list. + ### The register boundary (`ScopeResolver` contract) The seam between this authorization server and the membership register is one interface, @@ -163,7 +170,7 @@ Endpoints are registered in [`routes/router.go`](routes/router.go). The two opti | `GET /signin/{name}` | The page's stylesheet and typeface, and the operator's mark | anonymous | | `GET /callback` | Handle the identity-provider redirect: exchange the code, read claims, resolve the person, establish a session, mint a single-use app authorization code. A program passing several providers serves one such path per provider, each accepting only the answers to sign-ins sent to its own provider | state-verified (path configurable) | | `GET /logout` | The browser's leg of a sign-out (`client_id`, `redirect_uri`, optional `login_method`): send the browser to `redirect_uri`, which must be on the client's `post_logout_redirect_uris` (a sign-in return is not a sign-out landing). For a method listed as federated — the eParaksts profile's methods, or `OIDC_UPSTREAM_METHODS_FEDERATED` for a generic provider — it goes through the identity provider's logout first, so the session the provider keeps in the browser ends too; any other method signs out locally and leaves the provider's session alone. It takes no value naming a session: the client ends its own with `POST /revoke` first. The browser's single sign-on cookie, when it holds one, ends that shared session and every session signed in under it, and is cleared | anonymous (`redirect_uri` allowlisted) | -| `POST /token` | OAuth token endpoint — `authorization_code` \| `client_credentials` (optional `tenant=`: a service account acting for the organisation it is a member of) \| `refresh_token` (with the `client_id` the token was issued to) \| `urn:ietf:params:oauth:grant-type:token-exchange`. Every hop requires a valid DPoP proof. A confidential client proves itself at every grant with its secret, by HTTP Basic (`client_secret_basic`) or in the form (`client_secret_post`), never both in one request, and at the code exchange before the code is spent; a public client sends none | PKCE / client secret / refresh token + client + session key / subject token — all + DPoP | +| `POST /token` | OAuth token endpoint — `authorization_code` \| `client_credentials` (optional `tenant=`: a service account acting for the organisation it is a member of) \| `refresh_token` (with the `client_id` the token was issued to) \| `urn:ietf:params:oauth:grant-type:token-exchange`. Every hop requires a valid DPoP proof. A confidential client proves itself at every grant with its secret, by HTTP Basic (`client_secret_basic`) or in the form (`client_secret_post`), never both in one request, and at the code exchange before the code is spent; a public client sends none. A person in several organisations is answered `memberships` (each organisation's `tenant` id and `name`) at the code exchange and at every refresh, chosen or not, beside the unchanged `tenants`; a person in one organisation gets neither | PKCE / client secret / refresh token + client + session key / subject token — all + DPoP | | `POST /revoke` | End a session server to server ([RFC 7009]): `token` (the refresh token), `client_id`, optional `token_type_hint` (ignored). `200` when ended or when the token is unknown; `401` for another client's token, a proof of another key, or a confidential client without its secret; `503` when the store cannot be read | the session's own client (its secret, when confidential) + its DPoP key | | `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) | @@ -626,7 +633,7 @@ can be stated alongside the country. | `AUDIT_ISSUER_URL` | — (⇒ `AUTH_ISSUER_URL`) | Issuer base for the outbound token mint (set to an in-cluster URL when the public issuer is unreachable) | | `WEBEID_ENGINE_URL` | — (empty ⇒ `/webeid/*` not registered) | web-eid engine base; `/auth/validate` is called server-to-server with a service token | | `WEBEID_AUDIENCE` / `WEBEID_SCOPE` | `svc:web-eid` / `webeid:validate` | Audience/scope for the engine call | -| `ROLEBYTE_URL` | — (empty ⇒ standalone: each client's baseline scopes, no service accounts) | Membership register base — setting it wires the register (see "Supported configurations"). When set, every token issue of a person whose client requires a membership (first issue and refresh) claims the person's pending invitations and mints their register-resolved `group:level` scopes and tenant instead of a baseline — no membership is **refused** (403 `err:membership:notMember`), several are the person's to choose from (the token response's `tenants`), and an unreachable register fails the issuance closed (502), never an empty-scope token; a client whose row says `membership_required: false` keeps its people on the baseline and never touches the register. Every tenant-named `client_credentials` issue is resolved here too. The address is the register's **sign-in listener** (`http://rolebyte:8081` in the stacks), not its main port. Each call carries a token this service mints for it, naming the person and `AUDIT_CLIENT_ID` as the acting client, which must be the register's `SIGN_IN_CLIENT`; no registry grant for `membership:claim` or `membership:resolve` is needed, and none may exist | +| `ROLEBYTE_URL` | — (empty ⇒ standalone: each client's baseline scopes, no service accounts) | Membership register base — setting it wires the register (see "Supported configurations"). When set, every token issue of a person whose client requires a membership (first issue and refresh) claims the person's pending invitations and mints their register-resolved `group:level` scopes and tenant instead of a baseline — no membership is **refused** (403 `err:membership:notMember`), several are the person's to choose from (the token response's `tenants`, and `memberships` with each one's id and name), and an unreachable register fails the issuance closed (502), never an empty-scope token; a client whose row says `membership_required: false` keeps its people on the baseline and never touches the register. Every tenant-named `client_credentials` issue is resolved here too. The address is the register's **sign-in listener** (`http://rolebyte:8081` in the stacks), not its main port. Each call carries a token this service mints for it, naming the person and `AUDIT_CLIENT_ID` as the acting client, which must be the register's `SIGN_IN_CLIENT`; no registry grant for `membership:claim` or `membership:resolve` is needed, and none may exist | | `ROLEBYTE_AUDIENCE` | `svc:rolebyte` | Audience for the membership calls | | `DEMO_DIR` | — | Serve a static demo SPA under `/demo` — development | diff --git a/rolebyte/rolebyte.go b/rolebyte/rolebyte.go index 16d9e4f..fe3bece 100644 --- a/rolebyte/rolebyte.go +++ b/rolebyte/rolebyte.go @@ -82,8 +82,12 @@ type Minter func(subject, audience, scope, actor, thumbprint string) (string, er // HighScopes are scopes that count only when the person signed in at the highest // assurance level; the caller decides, from the session's level, whether they // are added. An older register sends none, and the list is then empty. +// +// TenantName is the organisation's name as the register holds it. It is empty +// when the register sends none, which an older register does not. type Membership struct { TenantID string + TenantName string Scopes []string HighScopes []string } @@ -187,8 +191,11 @@ func (r *Resolver) Admit(ctx *azugo.Context, subjectKey string, login DirectoryL } type membership struct { - TenantID string `json:"tenantId"` - Scopes []string `json:"scopes"` + TenantID string `json:"tenantId"` + // TenantName is the organisation's name. Absent or empty decodes to an + // empty name: a register that does not send it changes nothing. + TenantName string `json:"tenantName"` + Scopes []string `json:"scopes"` // HighScopes are the scopes that count only on a high-assurance sign-in. // Absent, null or empty all decode to no scopes: a register that does not // send the member changes nothing. diff --git a/rolebyte/rolebyte_test.go b/rolebyte/rolebyte_test.go index 56e957d..a97812d 100644 --- a/rolebyte/rolebyte_test.go +++ b/rolebyte/rolebyte_test.go @@ -254,6 +254,36 @@ func TestAdmitSendsOnlyWhatTheLoginKnows(t *testing.T) { qt.Check(t, qt.DeepEquals(body, map[string]string{"issuer": "https://login.example/t", "displayName": "Anna"})) } +// The organisation's name is read when the register sends one; an empty name and +// an absent key both give an empty name and no error. +func TestMembershipsDecodeTheOrganisationsName(t *testing.T) { + for name, tc := range map[string]struct { + member string + want string + }{ + "present": {`"tenantName":"Alpha Ltd",`, "Alpha Ltd"}, + "empty": {`"tenantName":"",`, ""}, + "absent": {``, ""}, + } { + t.Run(name, func(t *testing.T) { + reg := newSignInRegister(t, map[string]func(w http.ResponseWriter){ + doorClaims: answerJSON(`{"claimed":[]}`), + doorMemberships: answerJSON(`{"subjectKey":"sub:` + annaSub + `","memberships":[{"tenantId":"t1",` + + tc.member + `"scopes":["a:b"]}]}`), + }) + r, _ := reg.resolver() + + inRequest(t, func(ctx *azugo.Context) { + got, err := r.Memberships(ctx, PersonKey(annaSub)) + qt.Assert(t, qt.IsNil(err)) + qt.Assert(t, qt.HasLen(got, 1)) + qt.Check(t, qt.Equals(got[0].TenantID, "t1")) + qt.Check(t, qt.Equals(got[0].TenantName, tc.want)) + }) + }) + } +} + // The high-only list is read leniently: present, absent (an older register), // null and empty all decode, and only a present, non-empty list holds scopes. func TestMembershipsDecodeTheHighOnlyScopes(t *testing.T) { diff --git a/routes/response/response.go b/routes/response/response.go index b45175d..389dcab 100644 --- a/routes/response/response.go +++ b/routes/response/response.go @@ -27,6 +27,19 @@ type Token struct { // carries no tenant and no scopes until the login is repeated with the chosen // `tenant=`. Absent whenever the token carries a tenant, or needs none. Tenants []string `json:"tenants,omitempty"` + // Memberships lists, with each one's name, every organisation the person may + // act under, whenever the register answered more than one for them at this + // issue, whether or not one was chosen. Absent for a person in one + // organisation, and never in a refused answer or a service's token. + Memberships []Membership `json:"memberships,omitempty"` +} + +// Membership is one organisation a person may act under: its id and its name. +// The name is empty for an organisation the register holds none for; the key is +// always present. +type Membership struct { + Tenant string `json:"tenant"` + Name string `json:"name"` } // Capabilities is the signing-capability set of a logged-in session: the diff --git a/routes/token.go b/routes/token.go index 0e2008e..58f501c 100644 --- a/routes/token.go +++ b/routes/token.go @@ -37,6 +37,24 @@ type membershipOutcome struct { scopes []string tenant string choices []string + // listed is every membership the register answered, in its order, when it + // answered more than one; empty otherwise. + listed []rolebyte.Membership +} + +// membershipList is the answer's `memberships`: the organisations of a person +// in several, each with its name. Nil for anyone else. +func (o membershipOutcome) membershipList() []response.Membership { + if len(o.listed) == 0 { + return nil + } + + out := make([]response.Membership, 0, len(o.listed)) + for _, m := range o.listed { + out = append(out, response.Membership{Tenant: m.TenantID, Name: m.TenantName}) + } + + return out } // userScopes answers what a user token should carry. The public client the @@ -91,6 +109,11 @@ func (r *router) userScopes(ctx *azugo.Context, sess *session.Session, clientID, } } + var listed []rolebyte.Membership + if len(memberships) > 1 { + listed = memberships + } + chosen, choices := chooseMembership(memberships, tenantHint) switch { case len(memberships) == 0, chosen == nil && tenantHint != "": @@ -104,7 +127,7 @@ func (r *router) userScopes(ctx *azugo.Context, sess *session.Session, clientID, case chosen == nil: // Several organisations and none named: the choice is the person's. // The token carries no tenant and no scopes until they make it. - return membershipOutcome{choices: choices}, true + return membershipOutcome{choices: choices, listed: listed}, true } // The scopes that count only on a high sign-in go to a client that is set to @@ -113,7 +136,7 @@ func (r *router) userScopes(ctx *azugo.Context, sess *session.Session, clientID, scopes, dropped := withHighScopes(chosen, sess.LoA, client.HighScopes) warnDroppedScopes(ctx, chosen.TenantID, dropped) - return membershipOutcome{scopes: scopes, tenant: chosen.TenantID}, true + return membershipOutcome{scopes: scopes, tenant: chosen.TenantID, listed: listed}, true } // withHighScopes answers the scopes a person's token carries from the chosen @@ -441,6 +464,7 @@ func (r *router) grantAuthorizationCode(ctx *azugo.Context, thumbprint string) { RefreshToken: refresh, IDToken: idToken, Tenants: outcome.choices, + Memberships: outcome.membershipList(), // The login-captured signing capabilities ride the code exchange (and // only the code exchange — a refresh re-issues a token, it is not a // new identification), so the caller can hold them for the session. @@ -677,6 +701,7 @@ func (r *router) grantRefreshToken(ctx *azugo.Context, thumbprint string) { ExpiresIn: exp, RefreshToken: refresh, Tenants: outcome.choices, + Memberships: outcome.membershipList(), }) } diff --git a/routes/token_memberships_test.go b/routes/token_memberships_test.go new file mode 100644 index 0000000..89c1532 --- /dev/null +++ b/routes/token_memberships_test.go @@ -0,0 +1,525 @@ +package routes + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "net/url" + "sort" + "strings" + "sync" + "testing" + "time" + + authbytecore "github.com/go-make-bytes/authbyte" + "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" + "github.com/go-quicktest/qt" + "github.com/valyala/fasthttp" +) + +// named is a membership of an organisation with a name, whose roles grant the +// scopes given. +func named(tenant, name string, scopes ...string) rolebyte.Membership { + return rolebyte.Membership{TenantID: tenant, TenantName: name, Scopes: scopes} +} + +// withRegister is the setup that gives a test app a register answering from f. +func withRegister(f *fakeResolver) func(*authbytecore.App) { + return func(a *authbytecore.App) { a.SetScopeResolver(f) } +} + +// seedSignInNaming is seedSignIn for a sign-in at the given assurance level +// whose request named an organisation (tenant is empty when it named none). +func seedSignInNaming(t *testing.T, mem *sessiontest.Memory, clientID, redirectURI, tenant, loa string) signIn { + t.Helper() + + in := signIn{sid: randomToken(24), code: randomToken(24), verifier: randomToken(32)} + sum := sha256.Sum256([]byte(in.verifier)) + + ctx := context.Background() + qt.Assert(t, qt.IsNil(mem.CreateSession(ctx, in.sid, &session.Session{ + Subject: testPersonSub(5), + LoA: loa, + LoginMethod: "webEid", + }, sessionLifetime))) + qt.Assert(t, qt.IsNil(mem.SaveAppCode(ctx, in.code, &session.AppCode{ + SessionID: in.sid, + CodeChallenge: base64.RawURLEncoding.EncodeToString(sum[:]), + CodeChallengeMethod: "S256", + ClientID: clientID, + RedirectURI: redirectURI, + Tenant: tenant, + }, time.Minute))) + + return in +} + +// exchanged signs a person in at product-spa, naming tenant (or none), and answers +// the sign-in with the code exchange's status and body. +func exchanged(t *testing.T, mem *sessiontest.Memory, e *edge, tenant string) (signIn, int, map[string]any) { + t.Helper() + + in := seedSignInNaming(t, mem, "product-spa", productRedirect, tenant, "high") + status, body := e.exchange(in, "product-spa", productRedirect) + + return in, status, body +} + +// listed is the organisations a token answer lists in `memberships`, in the order +// answered, as id then name; each entry has exactly the keys `tenant` and `name`. +func listed(t *testing.T, body map[string]any) [][2]string { + t.Helper() + + list, ok := body["memberships"].([]any) + qt.Assert(t, qt.IsTrue(ok), qt.Commentf("%s", body["_raw"])) + + out := make([][2]string, 0, len(list)) + for _, item := range list { + m, ok := item.(map[string]any) + qt.Assert(t, qt.IsTrue(ok), qt.Commentf("%s", body["_raw"])) + qt.Check(t, qt.DeepEquals(keysOf(m), []string{"name", "tenant"})) + id, _ := m["tenant"].(string) + name, _ := m["name"].(string) + out = append(out, [2]string{id, name}) + } + + return out +} + +// keysOf is the sorted set of keys of an answer, without the test's own `_raw`. +func keysOf(body map[string]any) []string { + keys := make([]string, 0, len(body)) + for k := range body { + if k != "_raw" { + keys = append(keys, k) + } + } + sort.Strings(keys) + + return keys +} + +// scopesOf is the scopes of an answer's access token. +func scopesOf(t *testing.T, body map[string]any) []string { + t.Helper() + + tok, _ := body["access_token"].(string) + s, _ := tokenClaims(t, tok)["scope"].(string) + + return strings.Fields(s) +} + +// tenantOf is the tenant of an answer's access token ("" when it has none). +func tenantOf(t *testing.T, body map[string]any) string { + t.Helper() + + tok, _ := body["access_token"].(string) + s, _ := tokenClaims(t, tok)["tenant"].(string) + + return s +} + +// refused checks the refusal of a person who is a member nowhere they named: 403 +// with the code, and a body that holds no token, no organisation and no list. +func refused(t *testing.T, status int, body map[string]any, what ...string) { + t.Helper() + + raw, _ := body["_raw"].(string) + qt.Check(t, qt.Equals(status, fasthttp.StatusForbidden), qt.Commentf("%s", raw)) + qt.Check(t, qt.StringContains(raw, "err:membership:notMember")) + for _, s := range append([]string{"access_token", "memberships", "tenants"}, what...) { + qt.Check(t, qt.IsFalse(strings.Contains(raw, s)), qt.Commentf("%q in %s", s, raw)) + } +} + +const ( + orgA = "01TENANTAAAAAAAAAAAAAAAAAA" + orgB = "01TENANTBBBBBBBBBBBBBBBBBB" + orgC = "01TENANTCCCCCCCCCCCCCCCCCC" +) + +// the answer of a code exchange that carries a refresh token and nothing more. +var plainAnswerKeys = []string{"access_token", "expires_in", "refresh_token", "token_type"} + +// A person in two organisations who names none is answered a token with no +// tenant and no scope, the ids in `tenants` and both organisations with their +// names in `memberships`, in the register's order. +func TestTwoMembershipsNoneNamedListsBothByName(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + named(orgB, "Beta Ltd", "b:b"), + named(orgA, "Alpha Ltd", "a:a"), + }} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + _, status, body := exchanged(t, mem, e, "") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + + qt.Check(t, qt.Equals(tenantOf(t, body), "")) + qt.Check(t, qt.HasLen(scopesOf(t, body), 0)) + qt.Check(t, qt.DeepEquals(body["tenants"], any([]any{orgB, orgA}))) + qt.Check(t, qt.DeepEquals(listed(t, body), [][2]string{{orgB, "Beta Ltd"}, {orgA, "Alpha Ltd"}})) +} + +// One of two organisations named on the code: its token and its scopes only, +// both organisations listed, no `tenants`. +func TestTwoMembershipsOneNamedListsBothAndMintsTheNamedOne(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + named(orgA, "Alpha Ltd", "a:a"), + named(orgB, "Beta Ltd", "b:b"), + }} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + _, status, body := exchanged(t, mem, e, orgB) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + + qt.Check(t, qt.Equals(tenantOf(t, body), orgB)) + qt.Check(t, qt.DeepEquals(scopesOf(t, body), []string{"b:b"})) + qt.Check(t, qt.IsFalse(strings.Contains(strings.Join(scopesOf(t, body), " "), "a:a"))) + qt.Check(t, qt.DeepEquals(listed(t, body), [][2]string{{orgA, "Alpha Ltd"}, {orgB, "Beta Ltd"}})) + _, has := body["tenants"] + qt.Check(t, qt.IsFalse(has)) +} + +// A person in one organisation, naming none or naming it, is answered with the +// keys they always were: neither `memberships` nor `tenants`. +func TestOneMembershipAnswersTheKeysItAlwaysDid(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{named(orgA, "Alpha Ltd", "a:a")}} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + for name, tenant := range map[string]string{"none named": "", "named": orgA} { + _, status, body := exchanged(t, mem, e, tenant) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s: %s", name, body["_raw"])) + + qt.Check(t, qt.DeepEquals(keysOf(body), plainAnswerKeys), qt.Commentf("%s", name)) + raw := body["_raw"].(string) + qt.Check(t, qt.IsFalse(strings.Contains(raw, "memberships")), qt.Commentf("%s", name)) + qt.Check(t, qt.IsFalse(strings.Contains(raw, "tenants")), qt.Commentf("%s", name)) + qt.Check(t, qt.Equals(tenantOf(t, body), orgA)) + } +} + +// A third organisation named: refused, and the answer holds no token, no +// organisation's id, no name and no list. +func TestANamedOrganisationTheyAreNotInIsRefusedWithNothingListed(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + named(orgA, "Alpha Ltd", "a:a"), + named(orgB, "Beta Ltd", "b:b"), + }} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + _, status, body := exchanged(t, mem, e, orgC) + + refused(t, status, body, orgA, orgB, "Alpha Ltd", "Beta Ltd") +} + +// A request that names an organisation and is answered from the browser's +// single sign-on session with no page: its code, exchanged, gives the named +// organisation's token, and both organisations are listed. +func TestASingleSignOnAnswerHonoursTheNamedOrganisation(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + named(orgA, "Alpha Ltd", "a:a"), + named(orgB, "Beta Ltd", "b:b"), + }} + app, _, _ := sharedApp(t, fake) + tc := app.TestClient() + signInByCard(t, tc, "plain-card", plainReturn, annasCard) + + verifier, challenge := pkce() + a := authorizeIn(t, tc, "second-app", secondReturn, url.Values{"code_challenge": {challenge}, "tenant": {orgB}}) + code := codeAt(t, a, secondReturn) + qt.Assert(t, qt.Not(qt.Equals(code, "")), qt.Commentf("%d %s %s", a.status, a.location, a.body)) + + status, body := newEdge(t, app).exchange(signIn{code: code, verifier: verifier}, "second-app", secondReturn) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + qt.Check(t, qt.Equals(tenantOf(t, body), orgB)) + qt.Check(t, qt.DeepEquals(scopesOf(t, body), []string{"b:b"})) + qt.Check(t, qt.DeepEquals(listed(t, body), [][2]string{{orgA, "Alpha Ltd"}, {orgB, "Beta Ltd"}})) +} + +// With prompt=login, and with max_age=0, the request is not answered from the +// single sign-on session; after the sign-in on the page the code's organisation is +// the named one and the exchanged token is for it. +func TestAFreshSignInKeepsTheNamedOrganisation(t *testing.T) { + for name, extra := range map[string]url.Values{ + "prompt=login": {"prompt": {"login"}}, + "max_age=0": {"max_age": {"0"}}, + } { + t.Run(name, func(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + named(orgA, "Alpha Ltd", "a:a"), + named(orgB, "Beta Ltd", "b:b"), + }} + app, mem, _ := sharedApp(t, fake) + tc := app.TestClient() + signInByCard(t, tc, "plain-card", plainReturn, annasCard) + + // Not answered from the single sign-on session: the page is shown. + verifier, challenge := pkce() + q := url.Values{"code_challenge": {challenge}, "tenant": {orgB}} + for k, v := range extra { + q[k] = v + } + a := authorizeIn(t, tc, "second-app", secondReturn, q) + qt.Check(t, qt.Equals(codeAt(t, a, secondReturn), ""), qt.Commentf("%s", a.location)) + qt.Check(t, qt.Equals(a.status, fasthttp.StatusOK)) + + // Signing in on that page carries the same request. + req := requestFor("second-app", secondReturn, challenge) + for k, v := range q { + req[k] = v + } + p := showCardPage(t, tc, req) + qt.Assert(t, qt.Equals(p.status, fasthttp.StatusOK), qt.Commentf("%s", p.body)) + card := `{"nonce":"` + p.nonce + `","origin":"` + selfOriginInTests + `","code":"` + annasCard + `"}` + done := postCard(t, tc, p, p.state, card, p.token, selfOriginInTests) + code := codeAt(t, done, secondReturn) + qt.Assert(t, qt.Not(qt.Equals(code, "")), qt.Commentf("%d %s %s", done.status, done.location, done.body)) + + _, sess := sessionOf(t, mem, code) + qt.Check(t, qt.Not(qt.Equals(sess.Subject, ""))) + + status, body := newEdge(t, app).exchange(signIn{code: code, verifier: verifier}, "second-app", secondReturn) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + qt.Check(t, qt.Equals(tenantOf(t, body), orgB)) + qt.Check(t, qt.DeepEquals(scopesOf(t, body), []string{"b:b"})) + }) + } +} + +// A session issued for the one organisation its person was in keeps minting +// for it when the register later answers that one and another; the refresh lists +// both and carries no `tenants`. +func TestARefreshStaysInItsOrganisationWhenAnotherJoins(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{named(orgA, "Alpha Ltd", "a:a")}} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + _, status, body := exchanged(t, mem, e, "") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + qt.Check(t, qt.Equals(tenantOf(t, body), orgA)) + refresh, _ := body["refresh_token"].(string) + + fake.memberships = []rolebyte.Membership{named(orgA, "Alpha Ltd", "a:a"), named(orgB, "Beta Ltd", "b:b")} + status, body = e.refresh(refresh, "product-spa") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + + qt.Check(t, qt.Equals(tenantOf(t, body), orgA)) + qt.Check(t, qt.DeepEquals(scopesOf(t, body), []string{"a:a"})) + qt.Check(t, qt.DeepEquals(listed(t, body), [][2]string{{orgA, "Alpha Ltd"}, {orgB, "Beta Ltd"}})) + _, has := body["tenants"] + qt.Check(t, qt.IsFalse(has)) +} + +// A session issued for one of two organisations stays in it when the register +// later answers that one alone, and the refresh lists nothing. +func TestARefreshListsNothingOnceThePersonIsInOneOrganisation(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{named(orgA, "Alpha Ltd", "a:a"), named(orgB, "Beta Ltd", "b:b")}} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + _, status, body := exchanged(t, mem, e, orgA) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + refresh, _ := body["refresh_token"].(string) + + fake.memberships = []rolebyte.Membership{named(orgA, "Alpha Ltd", "a:a")} + status, body = e.refresh(refresh, "product-spa") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + + qt.Check(t, qt.Equals(tenantOf(t, body), orgA)) + qt.Check(t, qt.IsFalse(strings.Contains(body["_raw"].(string), "memberships"))) +} + +// A session issued for an organisation the register no longer answers for the +// person is refused at its refresh, with nothing in the body, and the stored +// session still names that organisation. +func TestARefreshForAnOrganisationTheyLeftIsRefused(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{named(orgA, "Alpha Ltd", "a:a")}} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + in, status, body := exchanged(t, mem, e, orgA) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + refresh, _ := body["refresh_token"].(string) + + fake.memberships = []rolebyte.Membership{named(orgB, "Beta Ltd", "b:b")} + status, body = e.refresh(refresh, "product-spa") + refused(t, status, body, orgA, orgB, "Alpha Ltd", "Beta Ltd") + + sess, err := mem.LoadSession(context.Background(), in.sid) + qt.Assert(t, qt.IsNil(err)) + qt.Check(t, qt.Equals(sess.Tenant, orgA)) +} + +// A session opened with two organisations and none named lists both at every +// refresh, with or without a `tenant` in the form, which a refresh ignores. +func TestARefreshOfASessionWithNoOrganisationListsBoth(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{named(orgA, "Alpha Ltd", "a:a"), named(orgB, "Beta Ltd", "b:b")}} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + _, status, body := exchanged(t, mem, e, "") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + refresh, _ := body["refresh_token"].(string) + + for name, extra := range map[string]string{"plain": "", "with tenant": orgA} { + form := url.Values{"grant_type": {"refresh_token"}, "refresh_token": {refresh}, "client_id": {"product-spa"}} + if extra != "" { + form.Set("tenant", extra) + } + status, body = e.post("/token", form) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s: %s", name, body["_raw"])) + + qt.Check(t, qt.Equals(tenantOf(t, body), ""), qt.Commentf("%s", name)) + qt.Check(t, qt.HasLen(scopesOf(t, body), 0), qt.Commentf("%s", name)) + qt.Check(t, qt.DeepEquals(body["tenants"], any([]any{orgA, orgB})), qt.Commentf("%s", name)) + qt.Check(t, qt.DeepEquals(listed(t, body), [][2]string{{orgA, "Alpha Ltd"}, {orgB, "Beta Ltd"}}), qt.Commentf("%s", name)) + } +} + +// Scopes that count only on a high sign-in, through the real token endpoint +// on a client set to carry them (extends the seam tests in +// token_highscopes_test.go, which prove the same rule below the endpoint): a high +// sign-in naming the organisation without one gets that organisation's scopes and +// not the other's high-only scope; one naming the organisation with one carries it; +// a sign-in below high naming it does not. +func TestHighOnlyScopesFollowTheNamedOrganisationAtTheEndpoint(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + withHigh(orgA, []string{"a:a"}, []string{highOnly}), + withHigh(orgB, []string{"b:b"}, nil), + }} + fake.memberships[0].TenantName = "Alpha Ltd" + fake.memberships[1].TenantName = "Beta Ltd" + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + const adminRedirect = "https://admin.example/callback" + + for _, c := range []struct { + name, tenant, loa string + want []string + }{ + {"high naming the organisation without one", orgB, "high", []string{"b:b"}}, + {"high naming the organisation with one", orgA, "high", []string{"a:a", highOnly}}, + {"below high naming the organisation with one", orgA, "substantial", []string{"a:a"}}, + } { + in := seedSignInNaming(t, mem, "admin-spa", adminRedirect, c.tenant, c.loa) + status, body := e.exchange(in, "admin-spa", adminRedirect) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s: %s", c.name, body["_raw"])) + qt.Check(t, qt.DeepEquals(scopesOf(t, body), c.want), qt.Commentf("%s", c.name)) + qt.Check(t, qt.Equals(tenantOf(t, body), c.tenant), qt.Commentf("%s", c.name)) + qt.Check(t, qt.HasLen(listed(t, body), 2), qt.Commentf("%s", c.name)) + } +} + +// An AI app's sign-in whose request names an organisation: the name is dropped +// as before and the token answer lists nothing, though the person is in two. +func TestAnAIAppsAnswerListsNoOrganisations(t *testing.T) { + d := aiApp(t) + d.register.memberships = []rolebyte.Membership{named(orgA, "Alpha Ltd", "plain:read"), named(orgB, "Beta Ltd", "plain:read")} + tc := d.app.TestClient() + verifier := randomToken(32) + + page := d.signInAs(t, tc, annasOID, aiAsk(verifier, url.Values{"tenant": {orgB}})) + qt.Assert(t, qt.Equals(page.status, fasthttp.StatusOK), qt.Commentf("%s", page.body)) + code := codeFrom(t, pick(t, tc, page, assistantWay(annasFirst))) + + status, out := tokenAt(t, d, "/token", codeExchange(code, verifier)) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%v", out)) + raw, _ := out["_status_text"].(string) + qt.Check(t, qt.IsFalse(strings.Contains(raw, "memberships")), qt.Commentf("%s", raw)) + qt.Check(t, qt.Equals(readToken(t, out["access_token"]).Tenant, annasFirst.TenantID)) +} + +// A service account in two organisations asking for one: as before, and the +// answer lists nothing. +func TestAServiceAccountsAnswerListsNoOrganisations(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + named(orgA, "Alpha Ltd", "things:read"), + named(orgB, "Beta Ltd", "things:read"), + }} + app, _ := signInApp(t, withRegister(fake)) + svc := newEdge(t, app) + svc.basic = []string{"svc:caller", "caller-secret"} + + status, body := svc.post("/token", url.Values{ + "grant_type": {"client_credentials"}, "client_id": {"svc:caller"}, "audience": {"svc:target"}, "tenant": {orgA}, + }) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + + qt.Check(t, qt.Equals(tenantOf(t, body), orgA)) + qt.Check(t, qt.DeepEquals(keysOf(body), []string{"access_token", "expires_in", "token_type"})) + qt.Check(t, qt.IsFalse(strings.Contains(body["_raw"].(string), "memberships"))) +} + +// steadyRegister answers one fixed list and records nothing, so requests at once +// may ask it. +type steadyRegister struct{ memberships []rolebyte.Membership } + +func (s steadyRegister) Memberships(*azugo.Context, string) ([]rolebyte.Membership, error) { + return s.memberships, nil +} + +func (steadyRegister) Admit(*azugo.Context, string, rolebyte.DirectoryLogin) (bool, error) { + return false, nil +} + +func (steadyRegister) Assistants(*azugo.Context, string) ([]rolebyte.Assistant, error) { + return nil, nil +} + +// A code presented a second time is refused as it is for anyone, and two +// refreshes at once both answer the list. +func TestASecondCodeAndTwoRefreshesForAPersonInTwoOrganisations(t *testing.T) { + register := steadyRegister{[]rolebyte.Membership{named(orgA, "Alpha Ltd", "a:a"), named(orgB, "Beta Ltd", "b:b")}} + app, mem := signInApp(t, func(a *authbytecore.App) { a.SetScopeResolver(register) }) + e := newEdge(t, app) + + in, status, body := exchanged(t, mem, e, "") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + refresh, _ := body["refresh_token"].(string) + + status, again := e.exchange(in, "product-spa", productRedirect) + qt.Check(t, qt.Equals(status, fasthttp.StatusUnauthorized), qt.Commentf("%s", again["_raw"])) + qt.Check(t, qt.IsFalse(strings.Contains(again["_raw"].(string), "memberships"))) + + var wg sync.WaitGroup + statuses := make([]int, 2) + answers := make([]map[string]any, 2) + for i := range statuses { + wg.Add(1) + go func() { + defer wg.Done() + statuses[i], answers[i] = e.refresh(refresh, "product-spa") + }() + } + wg.Wait() + + qt.Check(t, qt.DeepEquals(statuses, []int{fasthttp.StatusOK, fasthttp.StatusOK})) + for i, a := range answers { + qt.Check(t, qt.DeepEquals(listed(t, a), [][2]string{{orgA, "Alpha Ltd"}, {orgB, "Beta Ltd"}}), qt.Commentf("refresh %d", i)) + } +} + +// A name arrives unchanged, whatever it holds, and an organisation without one +// is listed with its key present and empty. +func TestANameArrivesUnchangedAndAnEmptyOneIsListedEmpty(t *testing.T) { + odd := "Ķekavas ābeļu dārzs \"Ž\" & " + strings.Repeat("ž", 167) + qt.Assert(t, qt.Equals(len([]rune(odd)), 200)) + + fake := &fakeResolver{memberships: []rolebyte.Membership{named(orgA, odd, "a:a"), named(orgB, "", "b:b")}} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + _, status, body := exchanged(t, mem, e, "") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + + qt.Check(t, qt.DeepEquals(listed(t, body), [][2]string{{orgA, odd}, {orgB, ""}})) + qt.Check(t, qt.StringContains(body["_raw"].(string), `"name":""`)) +} From a80642b5aef3fc793ca2734e28d419fc26f07aac Mon Sep 17 00:00:00 2001 From: GatisB Date: Sat, 14 Nov 2026 19:05:05 +0000 Subject: [PATCH 4/6] Replace an application's earlier session only when its new sign-in code is redeemed Signed-off-by: GatisB --- CHANGELOG.md | 9 ++ README.md | 6 +- routes/authorize.go | 4 +- routes/shared.go | 31 +++- routes/shared_redeem_test.go | 290 +++++++++++++++++++++++++++++++++++ routes/shared_test.go | 16 +- routes/signout_test.go | 47 ++++-- routes/token.go | 19 +++ routes/upstreams_test.go | 14 ++ 9 files changed, 403 insertions(+), 33 deletions(-) create mode 100644 routes/shared_redeem_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index af0e137..0561145 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,15 @@ does not. A registry that names a `deployment:` scope, or a baseline scope of no - **Built and run on Go 1.27.4.** +### Fixed + +- **An app's earlier session now ends when its new sign-in's code is redeemed, not when the code is issued.** Before, + a sign-in refused at the code exchange (for example `err:membership:notMember`, the person not being in the + organisation the sign-in named) had already ended the app's earlier session, so its next refresh was refused and + the person was signed out. Now the earlier session stays recorded under the browser's shared session and keeps + working, refresh included; the new session is ended on any refused redeem, and a redeem that finds the shared + session ended is refused. + ## v0.12.0 ### Added diff --git a/README.md b/README.md index e7c77ec..aee0d68 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,9 @@ the client. - **One person per browser.** Another person signing in in the same browser ends the earlier shared session and every session signed in under it; their refresh tokens are refused from then on. The same client signing in again in a - browser ends its own earlier session there. + browser replaces its own earlier session there when the new sign-in's code is redeemed; a sign-in refused at that + point (for example the person is not in the organisation it named) leaves the earlier session working, and a code + never redeemed changes nothing. A redeem that finds the shared session ended is refused. - **Signing out of one app signs out of every app.** `POST /revoke` of a session ends the shared session it was signed in under and, at once, every session signed in under that, of every client, single sign-on or not; `GET /logout` does the same for the shared session its cookie names and clears the cookie. Their refresh tokens are refused from @@ -450,7 +452,7 @@ The shared cache (Valkey or Redis, `CACHE_*`) holds only short-lived auth-flow a | `refresh:{hash}` | the session id and the client a refresh token was issued to | the session's remaining lifetime | keyed by the SHA-256 of the token; the token itself is never stored. Deleted at `/revoke` | | `dpop-proofs:{jti}` | seen DPoP proof ids | proof max-age + leeway | `SET … NX`: one-time-use across every instance | | `shared:{id}` | a browser's shared session: the person (subject, names, identity code, directory), each way they signed in with (method, level, `auth_time`, `amr`, its end), the hash of the cookie's secret | until its last way ends (`SESSION_TTL` after that way's sign-in) | created with `SET … NX`; a sign-in by the same person rewrites it with `SET … XX`; no tenant is kept on it | -| `shared-apps:{id}` | the sessions signed in under a shared session, by client | the shared session's end | written by one script that answers the client's earlier session, which is then ended; deleted with the shared session | +| `shared-apps:{id}` | the sessions signed in under a shared session, by client | the shared session's end | written when a code is redeemed, by one script that answers the client's earlier session, which is then ended; deleted with the shared session | A cache span in a trace is named by its operation and instance (`GET sessions`) and never by its key, because every key here is a session id, a token hash, a code, a login state or a proof id. Sessions and flows held under the earlier key layout (`flow:`, `code:`, `sess:`) are not read: taking this version signs everyone out once. diff --git a/routes/authorize.go b/routes/authorize.go index c07c894..114cdca 100644 --- a/routes/authorize.go +++ b/routes/authorize.go @@ -543,7 +543,7 @@ func (r *router) saveSignedIn(ctx *azugo.Context, client, sid string, sess *sess return true } - shared, until, err := r.joinShared(ctx, sess) + shared, _, err := r.joinShared(ctx, sess) if err != nil { ctx.Error(err) @@ -551,12 +551,12 @@ func (r *router) saveSignedIn(ctx *azugo.Context, client, sid string, sess *sess } sess.Shared = shared + // The session is recorded under the shared one when its code is redeemed. if err := r.Session().CreateSession(ctx, sid, sess, r.Config().SessionTTL); err != nil { ctx.Error(err) return false } - r.addSharedApp(ctx, shared, until, client, sid) return true } diff --git a/routes/shared.go b/routes/shared.go index f352262..0293a58 100644 --- a/routes/shared.go +++ b/routes/shared.go @@ -184,11 +184,12 @@ func (r *router) answerFromShared(ctx *azugo.Context, req *authorizeRequest) (an return true } - // The answer stands only once its session is recorded under the shared one - // and the shared one is still there: a sign-out that ended it meanwhile took - // its list of app sessions without this one, which no sign-out would reach. - // It is ended here and the request goes on as without a shared session. - if !r.addSharedApp(ctx, id, sh.ExpiresAt, req.clientID, sid) || !r.sharedLive(ctx, id) { + // The session is recorded under the shared one only when its code is + // redeemed, so the app's earlier session goes on until then. The answer + // stands only while the shared session is still there; one a sign-out ended + // is not answered, and the session made for it is ended here, the request + // going on as without a shared session. + if !r.sharedLive(ctx, id) { r.endAppSession(ctx, sid) return false @@ -284,8 +285,10 @@ func (r *router) keepPerson(sh *session.Shared, sess *session.Session) { // addSharedApp records sid as client's app session under the shared session id, // and ends the session that client had there before: the app replaced its own -// cookie with this sign-in, so nothing in the browser names that one any more. -// It answers whether sid was recorded, and so whether a sign-out reaches it. +// session with this one. It is called when the app redeems the code of sid, never +// at the code's issue, so a sign-in the app is refused leaves its earlier session +// working. It answers whether sid was recorded, and so whether a sign-out reaches +// it. func (r *router) addSharedApp(ctx *azugo.Context, id string, until time.Time, client, sid string) bool { previous, err := r.Session().PutSharedApp(ctx, id, client, sid, until) if err != nil { @@ -300,6 +303,20 @@ func (r *router) addSharedApp(ctx *azugo.Context, id string, until time.Time, cl return true } +// recordRedeemed records the app session sid, whose code was just redeemed, +// under the shared session it belongs to, and ends the app's earlier session +// there. It answers false when the shared session is gone or the record cannot be +// written, and the redeem is then refused: a session no sign-out reaches must not +// stay live. +func (r *router) recordRedeemed(ctx *azugo.Context, shared, client, sid string) bool { + sh, err := r.Session().LoadShared(ctx, shared) + if err != nil { + return false + } + + return r.addSharedApp(ctx, shared, sh.ExpiresAt, client, sid) && r.sharedLive(ctx, shared) +} + // sharedLive reports whether the shared session id is still there; a store that // cannot answer counts as no. func (r *router) sharedLive(ctx *azugo.Context, id string) bool { diff --git a/routes/shared_redeem_test.go b/routes/shared_redeem_test.go new file mode 100644 index 0000000..78aae0f --- /dev/null +++ b/routes/shared_redeem_test.go @@ -0,0 +1,290 @@ +package routes + +import ( + "context" + "encoding/json" + "net/url" + "strings" + "sync" + "testing" + + authbytecore "github.com/go-make-bytes/authbyte" + "github.com/go-make-bytes/authbyte/session" + "github.com/go-make-bytes/authbyte/session/sessiontest" + + "azugo.io/azugo" + "github.com/go-quicktest/qt" + "github.com/valyala/fasthttp" +) + +// The app's session is replaced under the browser's shared session when the code +// of its new sign-in is redeemed, never when the code is issued: a sign-in the +// app is refused leaves its earlier session recorded and working. + +// listedUnder is the app session recorded for client under tc's browser's shared +// session ("" when none). +func listedUnder(t *testing.T, mem *sessiontest.Memory, tc *azugo.TestClient, client string) string { + t.Helper() + + id, _ := sharedOf(t, mem, tc) + apps, err := mem.SharedApps(context.Background(), id) + qt.Assert(t, qt.IsNil(err)) + + return apps[client] +} + +// holdsRefreshGrant reports whether the store holds a refresh grant of the app +// session sid. +func holdsRefreshGrant(mem *sessiontest.Memory, sid string) bool { + for k, v := range mem.Entries() { + if strings.HasPrefix(k, "refresh:") && strings.Contains(v, sid) { + return true + } + } + + return false +} + +// sessionKeys are the keys of the live sessions in the store. +func sessionKeys(mem *sessiontest.Memory) []string { return mem.Keys("sess:") } + +// endingStore is the session store with a sign-out that lands between the +// browser's arrival and the answer: the shared session is ended just before the +// next read of it after arm. +type endingStore struct { + *sessiontest.Memory + + mu sync.Mutex + armed bool + reads int +} + +func (s *endingStore) arm() { + s.mu.Lock() + defer s.mu.Unlock() + s.armed, s.reads = true, 0 +} + +func (s *endingStore) LoadShared(ctx context.Context, id string) (*session.Shared, error) { + s.mu.Lock() + s.reads++ + end := s.armed && s.reads == 2 + s.mu.Unlock() + if end { + _, _ = s.EndShared(ctx, id) + } + + return s.Memory.LoadShared(ctx, id) +} + +// pageCodeFor signs the card in again through client's page, asking for tenant, +// and answers the code not yet redeemed and its verifier. +func pageCodeFor(t *testing.T, tc *azugo.TestClient, client, redirectURI, card, tenant string) (code, verifier string) { + t.Helper() + + verifier, challenge := pkce() + q := requestFor(client, redirectURI, challenge) + q.Set("prompt", "login") // the page, not an answer from the shared session + if tenant != "" { + q.Set("tenant", tenant) + } + p := showCardPage(t, tc, q) + qt.Assert(t, qt.Equals(p.status, fasthttp.StatusOK), qt.Commentf("%s", p.body)) + b, _ := json.Marshal(map[string]string{"nonce": p.nonce, "origin": selfOriginInTests, "code": card}) + a := postCard(t, tc, p, p.state, string(b), p.token, selfOriginInTests) + code = codeAt(t, a, redirectURI) + qt.Assert(t, qt.Not(qt.Equals(code, "")), qt.Commentf("%d %s %s", a.status, a.location, a.body)) + + return code, verifier +} + +// answeredCodeFor is client answered from the shared session, asking for tenant, +// its code not yet redeemed, and its verifier. +func answeredCodeFor(t *testing.T, tc *azugo.TestClient, client, redirectURI, tenant string) (code, verifier string) { + t.Helper() + + verifier, challenge := pkce() + extra := url.Values{"code_challenge": {challenge}} + if tenant != "" { + extra.Set("tenant", tenant) + } + a := authorizeIn(t, tc, client, redirectURI, extra) + code = codeAt(t, a, redirectURI) + qt.Assert(t, qt.Not(qt.Equals(code, "")), qt.Commentf("%s: %d %s %s", client, a.status, a.location, a.body)) + + return code, verifier +} + +// codeIssuer issues a code for an app that already holds a session. +type codeIssuer func(t *testing.T, tc *azugo.TestClient, tenant string) (code, verifier string) + +// issuers are the two places a code is issued from: a reuse of the shared +// session, and the sign-in page. +var issuers = map[string]codeIssuer{ + "answered from the shared session": func(t *testing.T, tc *azugo.TestClient, tenant string) (string, string) { + return answeredCodeFor(t, tc, "plain-card", plainReturn, tenant) + }, + "completed at the sign-in page": func(t *testing.T, tc *azugo.TestClient, tenant string) (string, string) { + return pageCodeFor(t, tc, "plain-card", plainReturn, annasCard, tenant) + }, +} + +func memberOfOne() *fakeResolver { return &fakeResolver{memberships: memberships(orgA)} } + +func TestAnAppsEarlierSessionEndsWhenTheNewCodeIsRedeemed(t *testing.T) { + for name, issue := range issuers { + app, mem, _ := sharedApp(t, memberOfOne()) + tc := app.TestClient() + earlier := cardSignedIn(t, app, mem, tc, "plain-card", plainReturn, annasCard) + + code, verifier := issue(t, tc, "") + newSID, _ := sessionOf(t, mem, code) + qt.Check(t, qt.Equals(earlier.renews(), fasthttp.StatusOK), qt.Commentf("%s: before the redeem", name)) + qt.Check(t, qt.Equals(listedUnder(t, mem, tc, "plain-card"), earlier.sid), qt.Commentf("%s: listed before", name)) + + now := redeemed(t, app, mem, "plain-card", plainReturn, code, verifier) + qt.Check(t, qt.Equals(now.sid, newSID), qt.Commentf("%s", name)) + qt.Check(t, qt.Equals(earlier.renews(), fasthttp.StatusUnauthorized), qt.Commentf("%s: earlier after the redeem", name)) + qt.Check(t, qt.Equals(now.renews(), fasthttp.StatusOK), qt.Commentf("%s: new after the redeem", name)) + qt.Check(t, qt.Equals(listedUnder(t, mem, tc, "plain-card"), newSID), qt.Commentf("%s: listed after", name)) + } +} + +func TestARefusedRedeemLeavesTheAppsEarlierSessionWorking(t *testing.T) { + for name, issue := range issuers { + app, mem, _ := sharedApp(t, memberOfOne()) + tc := app.TestClient() + earlier := cardSignedIn(t, app, mem, tc, "plain-card", plainReturn, annasCard) + + // The person is in orgA only; the sign-in names orgB. + code, verifier := issue(t, tc, orgB) + newSID, _ := sessionOf(t, mem, code) + status, body := newEdge(t, app).exchange(signIn{code: code, verifier: verifier}, "plain-card", plainReturn) + qt.Check(t, qt.Equals(status, fasthttp.StatusForbidden), qt.Commentf("%s: %s", name, body["_raw"])) + qt.Check(t, qt.StringContains(body["_raw"].(string), "err:membership:notMember"), qt.Commentf("%s", name)) + + qt.Check(t, qt.Equals(earlier.renews(), fasthttp.StatusOK), qt.Commentf("%s: earlier still renews", name)) + qt.Check(t, qt.Equals(listedUnder(t, mem, tc, "plain-card"), earlier.sid), qt.Commentf("%s: earlier still listed", name)) + _, err := mem.LoadSession(context.Background(), newSID) + qt.Check(t, qt.ErrorIs(err, session.ErrNotFound), qt.Commentf("%s: the new session is gone", name)) + + // A sign-out still reaches the earlier session. + out := got(t)(tc.Get("/logout?client_id=plain-card&redirect_uri=" + url.QueryEscape("https://plain.example/"))) + qt.Check(t, qt.Not(qt.Equals(out.location, "")), qt.Commentf("%s", name)) + earlier.ended(t, mem) + } +} + +func TestACodeNeverRedeemedLeavesTheAppsEarlierSessionWorking(t *testing.T) { + for name, issue := range issuers { + app, mem, _ := sharedApp(t, memberOfOne()) + tc := app.TestClient() + earlier := cardSignedIn(t, app, mem, tc, "plain-card", plainReturn, annasCard) + + code, _ := issue(t, tc, "") + newSID, newSess := sessionOf(t, mem, code) + + qt.Check(t, qt.Equals(earlier.renews(), fasthttp.StatusOK), qt.Commentf("%s", name)) + qt.Check(t, qt.Equals(listedUnder(t, mem, tc, "plain-card"), earlier.sid), qt.Commentf("%s", name)) + qt.Check(t, qt.Equals(newSess.RefreshKey, ""), qt.Commentf("%s: the new session holds no refresh grant", name)) + _, err := mem.LoadSession(context.Background(), newSID) + qt.Check(t, qt.IsNil(err), qt.Commentf("%s: it ends with its own expiry", name)) + } +} + +func TestASignOutBetweenTheIssueAndTheRedeemRefusesTheRedeem(t *testing.T) { + for name, issue := range issuers { + app, mem, _ := sharedApp(t, memberOfOne()) + tc := app.TestClient() + earlier := cardSignedIn(t, app, mem, tc, "plain-card", plainReturn, annasCard) + + code, verifier := issue(t, tc, "") + newSID, _ := sessionOf(t, mem, code) + qt.Check(t, qt.Equals(earlier.signsOut(), fasthttp.StatusOK), qt.Commentf("%s", name)) + + status, body := newEdge(t, app).exchange(signIn{code: code, verifier: verifier}, "plain-card", plainReturn) + qt.Check(t, qt.Equals(status, fasthttp.StatusUnauthorized), qt.Commentf("%s: %s", name, body["_raw"])) + qt.Check(t, qt.IsNil(body["access_token"]), qt.Commentf("%s", name)) + earlier.ended(t, mem) + _, err := mem.LoadSession(context.Background(), newSID) + qt.Check(t, qt.ErrorIs(err, session.ErrNotFound), qt.Commentf("%s: the new session is gone", name)) + qt.Check(t, qt.IsFalse(holdsRefreshGrant(mem, newSID)), qt.Commentf("%s: its refresh grant is gone", name)) + qt.Check(t, qt.HasLen(mem.Keys("refresh:"), 0), qt.Commentf("%s: no refresh grant of the app is left", name)) + } +} + +// A shared session that a sign-out ended between the browser's arrival and the +// answer is not answered from: no code, and the session made for the answer is +// ended, the request going on as without a shared session. +func TestASharedSessionEndedBeforeTheAnswerIsNotAnsweredFrom(t *testing.T) { + var ending *endingStore + app, mem, _ := sharedApp(t, memberOfOne(), func(a *authbytecore.App) { + ending = &endingStore{Memory: a.Session().(*sessiontest.Memory)} + a.SetSessionStore(ending) + }) + tc := app.TestClient() + cardSignedIn(t, app, mem, tc, "plain-card", plainReturn, annasCard) + before := sessionKeys(mem) + refreshBefore := mem.Keys("refresh:") + + ending.arm() + a := authorizeIn(t, tc, "second-app", secondReturn, nil) + qt.Check(t, qt.Equals(codeAt(t, a, secondReturn), ""), qt.Commentf("%d %s", a.status, a.location)) + qt.Check(t, qt.Equals(a.status, fasthttp.StatusOK)) + qt.Check(t, qt.HasLen(mem.Keys("code:"), 0)) + + // Only the session made for the answer is gone; the store's own end of the + // shared session leaves the first app session as it was. + qt.Check(t, qt.HasLen(sessionKeys(mem), len(before))) + qt.Check(t, qt.HasLen(mem.Keys("refresh:"), len(refreshBefore))) +} + +// A stolen code is refused whatever it is presented with: a wrong verifier, or +// another client. Each refusal ends the session made for the code and leaves the +// app's earlier session working and listed. +func TestAStolenCodeIsRefusedAndLeavesTheAppsEarlierSession(t *testing.T) { + for name, issue := range issuers { + for _, c := range []struct { + what string + client string + redirect string + verifier func(string) string + }{ + {"a wrong verifier", "plain-card", plainReturn, func(string) string { return randomToken(32) }}, + {"another client", "second-app", secondReturn, func(v string) string { return v }}, + } { + app, mem, _ := sharedApp(t, memberOfOne()) + tc := app.TestClient() + earlier := cardSignedIn(t, app, mem, tc, "plain-card", plainReturn, annasCard) + + code, verifier := issue(t, tc, "") + newSID, _ := sessionOf(t, mem, code) + status, body := newEdge(t, app).exchange(signIn{code: code, verifier: c.verifier(verifier)}, c.client, c.redirect) + qt.Check(t, qt.Equals(status, fasthttp.StatusUnauthorized), qt.Commentf("%s, %s: %s", name, c.what, body["_raw"])) + qt.Check(t, qt.IsNil(body["access_token"]), qt.Commentf("%s, %s", name, c.what)) + + qt.Check(t, qt.Equals(earlier.renews(), fasthttp.StatusOK), qt.Commentf("%s, %s: earlier still renews", name, c.what)) + qt.Check(t, qt.Equals(listedUnder(t, mem, tc, "plain-card"), earlier.sid), qt.Commentf("%s, %s: earlier still listed", name, c.what)) + _, err := mem.LoadSession(context.Background(), newSID) + qt.Check(t, qt.ErrorIs(err, session.ErrNotFound), qt.Commentf("%s, %s: the new session is gone", name, c.what)) + } + } +} + +func TestAFirstSignInIsRecordedWhenItsCodeIsRedeemed(t *testing.T) { + app, mem, _ := sharedApp(t, memberOfOne()) + tc := app.TestClient() + + a, verifier := signInByCard(t, tc, "plain-card", plainReturn, annasCard) + code := codeAt(t, a, plainReturn) + qt.Assert(t, qt.Not(qt.Equals(code, ""))) + qt.Check(t, qt.Equals(listedUnder(t, mem, tc, "plain-card"), ""), qt.Commentf("not listed before the redeem")) + + first := redeemed(t, app, mem, "plain-card", plainReturn, code, verifier) + qt.Check(t, qt.Equals(listedUnder(t, mem, tc, "plain-card"), first.sid)) + qt.Check(t, qt.Equals(first.renews(), fasthttp.StatusOK)) + + out := got(t)(tc.Get("/logout?client_id=plain-card&redirect_uri=" + url.QueryEscape("https://plain.example/"))) + qt.Check(t, qt.Not(qt.Equals(out.location, ""))) + first.ended(t, mem) +} diff --git a/routes/shared_test.go b/routes/shared_test.go index d044d27..8c3d027 100644 --- a/routes/shared_test.go +++ b/routes/shared_test.go @@ -640,17 +640,21 @@ func TestAnotherPersonEndsTheFirstPersonsApps(t *testing.T) { // 35: the same app signs in twice, the same person; an app that is not single // sign-on shows the page each time, as a repeat sign-in does. - first, _ := signInByCard(t, tc, "sso-off", offReturn, annasCard) - firstSID, _ := sessionOf(t, mem, codeAt(t, first, offReturn)) - again, _ := signInByCard(t, tc, "sso-off", offReturn, annasCard) - againSID, _ := sessionOf(t, mem, codeAt(t, again, offReturn)) + // The earlier session ends when the new sign-in's code is redeemed. + first := cardSignedIn(t, app, mem, tc, "sso-off", offReturn, annasCard) + again, againVerifier := signInByCard(t, tc, "sso-off", offReturn, annasCard) + againCode := codeAt(t, again, offReturn) + firstSID := first.sid _, err := mem.LoadSession(context.Background(), firstSID) + qt.Check(t, qt.IsNil(err)) + againApp := redeemed(t, app, mem, "sso-off", offReturn, againCode, againVerifier) + againSID := againApp.sid + _, err = mem.LoadSession(context.Background(), firstSID) qt.Check(t, qt.ErrorIs(err, session.ErrNotFound)) _, err = mem.LoadSession(context.Background(), againSID) qt.Check(t, qt.IsNil(err)) - answered := authorizeIn(t, tc, "second-app", secondReturn, nil) - secondSID, _ := sessionOf(t, mem, codeAt(t, answered, secondReturn)) + secondSID := answeredApp(t, app, mem, tc, "second-app", secondReturn).sid annasShared, _ := sharedOf(t, mem, tc) // 33: Jānis signs in in the same browser. diff --git a/routes/signout_test.go b/routes/signout_test.go index 6ab7f0d..205c511 100644 --- a/routes/signout_test.go +++ b/routes/signout_test.go @@ -203,10 +203,10 @@ func TestTwoAppsSigningOutAtOnceEndEverythingOnce(t *testing.T) { qt.Check(t, qt.Equals(ended[0].Attributes["sessions"], 3)) } -// racingStore is the session store with a sign-out that lands while an answer -// from the shared session is being given: after the answer read the shared -// session and wrote its new app session, just before it records the app under -// the shared one. putFails makes recording the app fail instead. +// racingStore is the session store with a sign-out that lands while a code is +// being redeemed: after the redeem read its session and minted its tokens, just +// before it records the app session under the shared one. putFails makes +// recording the app fail instead. type racingStore struct { *sessiontest.Memory @@ -240,12 +240,25 @@ func (s *racingStore) lastRecorded() string { return s.recorded[len(s.recorded)-1] } -// C7 case 13: an answer from the shared session given while a sign-out ends it -// does not outlive the sign-out: it finds the shared session gone once it has -// recorded its app, ends the session it made and shows the page, with no code. An -// answer whose app cannot be recorded under the shared session is not given -// either, since no sign-out would reach it. -func TestAnAnswerDuringASignOutDoesNotOutliveIt(t *testing.T) { +// answeredCode is the code of client answered from tc's browser's shared session +// with no page, not yet redeemed, and its verifier. +func answeredCode(t *testing.T, tc *azugo.TestClient, client, redirectURI string) (code, verifier string) { + t.Helper() + + verifier, challenge := pkce() + a := authorizeIn(t, tc, client, redirectURI, url.Values{"code_challenge": {challenge}}) + code = codeAt(t, a, redirectURI) + qt.Assert(t, qt.Not(qt.Equals(code, "")), qt.Commentf("%s: %d %s %s", client, a.status, a.location, a.body)) + + return code, verifier +} + +// A redeem that lands while a sign-out ends the shared session does not outlive +// the sign-out: it finds the shared session gone once it has recorded its app, +// ends the session it made and is refused, with no token. A redeem whose app +// cannot be recorded under the shared session is refused too, since no sign-out +// would reach it. +func TestARedeemDuringASignOutDoesNotOutliveIt(t *testing.T) { var racing *racingStore app, mem, _ := sharedApp(t, nil, func(a *authbytecore.App) { racing = &racingStore{Memory: a.Session().(*sessiontest.Memory)} @@ -254,27 +267,29 @@ func TestAnAnswerDuringASignOutDoesNotOutliveIt(t *testing.T) { tc := app.TestClient() plain := cardSignedIn(t, app, mem, tc, "plain-card", plainReturn, annasCard) + code, verifier := answeredCode(t, tc, "second-app", secondReturn) racing.mu.Lock() racing.signOut = func() { qt.Check(t, qt.Equals(plain.signsOut(), fasthttp.StatusOK)) } racing.mu.Unlock() - a := authorizeIn(t, tc, "second-app", secondReturn, nil) - qt.Check(t, qt.Equals(codeAt(t, a, secondReturn), ""), qt.Commentf("%d %s", a.status, a.location)) - qt.Check(t, qt.Equals(a.status, fasthttp.StatusOK)) + status, body := newEdge(t, app).exchange(signIn{code: code, verifier: verifier}, "second-app", secondReturn) + qt.Check(t, qt.Equals(status, fasthttp.StatusUnauthorized), qt.Commentf("%s", body["_raw"])) + qt.Check(t, qt.IsNil(body["access_token"])) _, err := mem.LoadSession(context.Background(), racing.lastRecorded()) qt.Check(t, qt.ErrorIs(err, session.ErrNotFound)) + qt.Check(t, qt.IsFalse(holdsRefreshGrant(mem, racing.lastRecorded())), qt.Commentf("its refresh grant is gone")) plain.ended(t, mem) other := app.TestClient() cardSignedIn(t, app, mem, other, "plain-card", plainReturn, annasCard) + code, verifier = answeredCode(t, other, "second-app", secondReturn) racing.mu.Lock() racing.putFails = true racing.mu.Unlock() - a = authorizeIn(t, other, "second-app", secondReturn, nil) - qt.Check(t, qt.Equals(codeAt(t, a, secondReturn), ""), qt.Commentf("%d %s", a.status, a.location)) - qt.Check(t, qt.Equals(a.status, fasthttp.StatusOK)) + status, body = newEdge(t, app).exchange(signIn{code: code, verifier: verifier}, "second-app", secondReturn) + qt.Check(t, qt.Equals(status, fasthttp.StatusUnauthorized), qt.Commentf("%s", body["_raw"])) _, err = mem.LoadSession(context.Background(), racing.lastRecorded()) qt.Check(t, qt.ErrorIs(err, session.ErrNotFound)) } diff --git a/routes/token.go b/routes/token.go index 58f501c..c3930be 100644 --- a/routes/token.go +++ b/routes/token.go @@ -361,6 +361,15 @@ func (r *router) grantAuthorizationCode(ctx *azugo.Context, thumbprint string) { return } + // The code is spent. A redeem refused from here on ends the session made for + // it, and leaves the app's earlier session recorded and working. + redeemedOK := false + defer func() { + if !redeemedOK { + r.endAppSession(ctx, appCode.SessionID) + } + }() + // Echo-check: client_id and redirect_uri must match what was registered at // authorization time ([RFC 6749 §4.1.3]). if appCode.ClientID != clientID || appCode.RedirectURI != redirectURI { @@ -455,6 +464,16 @@ func (r *router) grantAuthorizationCode(ctx *azugo.Context, thumbprint string) { } } + // The session replaces the app's earlier one under the browser's shared + // session only now that its code is redeemed. A shared session a sign-out + // ended meanwhile, or one that cannot be written, refuses the redeem. + if sess.Shared != "" && !r.recordRedeemed(ctx, sess.Shared, clientID, appCode.SessionID) { + ctx.Error(corehttp.UnauthorizedError{}) + + return + } + redeemedOK = true + r.Audit().UserTokenIssued(ctx, sess.Subject, sess.LoA, sess.LoginMethod, signIn.Audience, outcome.scopes) ctx.JSON(&response.Token{ diff --git a/routes/upstreams_test.go b/routes/upstreams_test.go index 70028dd..64feaa6 100644 --- a/routes/upstreams_test.go +++ b/routes/upstreams_test.go @@ -324,6 +324,17 @@ func sentTo(t *testing.T, a answer) (*url.URL, string) { return loc, loc.Query().Get("state") } +// listUnderShared lists the app session sid under tc's browser's shared session +// directly in the store, in place of the redeem of its code that would list it; +// these tests complete sign-ins without redeeming. +func listUnderShared(t *testing.T, mem *sessiontest.Memory, tc *azugo.TestClient, client, sid string) { + t.Helper() + + id, sh := sharedOf(t, mem, tc) + _, err := mem.PutSharedApp(context.Background(), id, client, sid, sh.ExpiresAt) + qt.Assert(t, qt.IsNil(err)) +} + // startDirect starts a sign-in for clientID asking for method by acr_values. func (d *twoLaneDeployment) startDirect(t *testing.T, tc *azugo.TestClient, clientID, redirectURI, method string, extra url.Values) (*url.URL, string) { t.Helper() @@ -665,6 +676,7 @@ func TestAnotherProviderWithoutACommonCodeIsAnotherPerson(t *testing.T) { first := codeAt(t, d.signInByEntra(t, tc, "mobile-and-entra", meReturn, "oid-4"), meReturn) qt.Assert(t, qt.Not(qt.Equals(first, ""))) firstSid, firstSess := sessionOf(t, d.mem, first) + listUnderShared(t, d.mem, tc, "mobile-and-entra", firstSid) second := codeAt(t, d.signInByEParaksts(t, tc, "mobile-and-entra", meReturn), meReturn) qt.Assert(t, qt.Not(qt.Equals(second, ""))) @@ -762,11 +774,13 @@ func TestASignOutEndsAppsOfEveryLane(t *testing.T) { byMobile := codeAt(t, d.signInByEParaksts(t, tc, "mobile-and-entra", meReturn), meReturn) qt.Assert(t, qt.Not(qt.Equals(byMobile, ""))) mobileSid, _ := sessionOf(t, d.mem, byMobile) + listUnderShared(t, d.mem, tc, "mobile-and-entra", mobileSid) a, _ := signInByCard(t, tc, "card-sso", cardsReturn, annasCard) byCard := codeAt(t, a, cardsReturn) qt.Assert(t, qt.Not(qt.Equals(byCard, "")), qt.Commentf("%d %s", a.status, a.body)) cardSid, _ := sessionOf(t, d.mem, byCard) + listUnderShared(t, d.mem, tc, "card-sso", cardSid) out := got(t)(tc.Get("/logout?client_id=mobile-and-entra&redirect_uri=" + url.QueryEscape("https://me.example/") + "&login_method=" + identity.LoginEParakstsMobile)) From f80dc00cc6626e4fa59e1cc5af13d0c7c523eef6 Mon Sep 17 00:00:00 2001 From: GatisB Date: Sun, 15 Nov 2026 17:03:17 +0000 Subject: [PATCH 5/6] Tell the register which company a token is issued for Signed-off-by: GatisB --- CHANGELOG.md | 6 ++ README.md | 4 +- app.go | 4 +- rolebyte/rolebyte.go | 20 +++++- rolebyte/rolebyte_test.go | 39 ++++++++++-- routes/shared.go | 2 +- routes/token.go | 19 +++++- routes/token_memberships_test.go | 2 +- routes/token_register_company_test.go | 91 +++++++++++++++++++++++++++ routes/token_rolebyte_test.go | 4 +- 10 files changed, 174 insertions(+), 17 deletions(-) create mode 100644 routes/token_register_company_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 0561145..894d46d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,12 @@ does not. A registry that names a `deployment:` scope, or a baseline scope of no ### Changed +- **The register is told which organisation a token is being issued for.** The lookup of a person's memberships + carries `{"tenant": ""}` when the sign-in names an organisation, when a refresh continues a session in one, and + when a service account asks for one, so the register can date the sign-in in that organisation alone. A name that is + not an organisation's id is not sent, and is answered as a name no membership matches. When none is named the + request is exactly as before. A register that ignores the body answers as it always did, and the tokens' scopes and + tenant are unchanged. - **Built and run on Go 1.27.4.** ### Fixed diff --git a/README.md b/README.md index aee0d68..083061e 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,9 @@ ship separately, so this boundary is a published contract: its own process for that call alone: the subject being signed in as `sub`, this service's client id (`AUDIT_CLIENT_ID`) as the acting client (`act`), the door's one scope, bound to the outbound client's DPoP key. The register answers for the token's subject and nobody else. No - token endpoint and no registry grant are involved. + token endpoint and no registry grant are involved. The memberships call may carry + `{"tenant":""}`, the organisation the token is issued for, and carries no body when none + is named or the name is not an organisation id. - **The answer is checked:** it names the subject it is about, and an answer about anyone else mints nothing, fails the issue closed (`502`) and raises an `authz.denied` security event (`kind: sign-in`), which a healthy deployment never produces. diff --git a/app.go b/app.go index dca33a1..e73a633 100644 --- a/app.go +++ b/app.go @@ -100,7 +100,9 @@ type App struct { // contract (answers, refusals, unreachability, compatibility) is in the // README's "Supported configurations" section. type ScopeResolver interface { - Memberships(ctx *azugo.Context, subjectKey string) ([]rolebyte.Membership, error) + // Tenant is the organisation the token will be issued for, empty when none is + // named; the register dates the sign-in in that organisation alone. + Memberships(ctx *azugo.Context, subjectKey, tenant string) ([]rolebyte.Membership, error) // Admit offers a person who authenticated through an organisation's own // directory to the register's admission door; true when a membership was // created or activated by the call. diff --git a/rolebyte/rolebyte.go b/rolebyte/rolebyte.go index fe3bece..e055a25 100644 --- a/rolebyte/rolebyte.go +++ b/rolebyte/rolebyte.go @@ -202,6 +202,12 @@ type membership struct { HighScopes []string `json:"highScopes"` } +// membershipsRequest is the body of the lookup when the organisation the token +// will be issued for is known. +type membershipsRequest struct { + Tenant string `json:"tenant"` +} + type resolveResponse struct { // SubjectKey is the key the register says this answer is about. SubjectKey string `json:"subjectKey"` @@ -275,9 +281,12 @@ func (r *Resolver) Assistants(ctx *azugo.Context, subjectKey string) ([]Assistan // its active memberships — the organisations it may act under, each with the // scopes its roles grant there. An empty answer means the subject holds no // membership; which one to mint, when there are several, is the caller's -// question. Any transport or service failure surfaces as an error — the caller +// question. Tenant is the organisation the token will be issued for, when the +// caller knows it: the register is told, so it dates the person's sign-in in +// that organisation alone. Empty names none and sends the request exactly as +// before. Any transport or service failure surfaces as an error — the caller // fails the token issue closed. -func (r *Resolver) Memberships(ctx *azugo.Context, subjectKey string) ([]Membership, error) { +func (r *Resolver) Memberships(ctx *azugo.Context, subjectKey, tenant string) ([]Membership, error) { if strings.TrimSpace(subjectKey) == "" { // Without a key there is nothing to look up — and every caller has one // (a platform subject or a client id), so this is a wiring fault, not a @@ -292,8 +301,13 @@ func (r *Resolver) Memberships(ctx *azugo.Context, subjectKey string) ([]Members return nil, err } + var in any + if tenant != "" { + in = membershipsRequest{Tenant: tenant} + } + var res resolveResponse - if err := r.call(ctx, subjectKey, scopeResolve, doorMemberships, nil, &res); err != nil { + if err := r.call(ctx, subjectKey, scopeResolve, doorMemberships, in, &res); err != nil { return nil, err } diff --git a/rolebyte/rolebyte_test.go b/rolebyte/rolebyte_test.go index a97812d..0c48729 100644 --- a/rolebyte/rolebyte_test.go +++ b/rolebyte/rolebyte_test.go @@ -164,7 +164,7 @@ func TestMembershipsAsksEachDoorWithATokenForThePerson(t *testing.T) { r, ac := reg.resolver() inRequest(t, func(ctx *azugo.Context) { - got, err := r.Memberships(ctx, PersonKey(annaSub)) + got, err := r.Memberships(ctx, PersonKey(annaSub), "") qt.Assert(t, qt.IsNil(err)) qt.Check(t, qt.DeepEquals(got, []Membership{{TenantID: "t1", Scopes: []string{"projects:read"}}})) }) @@ -184,6 +184,33 @@ func TestMembershipsAsksEachDoorWithATokenForThePerson(t *testing.T) { } } +// The lookup sends the organisation the token will be issued for as its body, +// and exactly the request it always sent when none is named: no body at all. +func TestMembershipsSendsTheOrganisationOnlyWhenOneIsNamed(t *testing.T) { + for name, tc := range map[string]struct{ tenant, wantBody string }{ + "named": {"01TENANTA", `{"tenant":"01TENANTA"}`}, + "none": {"", ""}, + } { + t.Run(name, func(t *testing.T) { + reg := newSignInRegister(t, map[string]func(w http.ResponseWriter){ + doorClaims: answerJSON(`{"claimed":[]}`), + doorMemberships: answerJSON(`{"subjectKey":"sub:` + annaSub + `","memberships":[]}`), + }) + r, _ := reg.resolver() + + inRequest(t, func(ctx *azugo.Context) { + _, err := r.Memberships(ctx, PersonKey(annaSub), tc.tenant) + qt.Assert(t, qt.IsNil(err)) + }) + + qt.Assert(t, qt.HasLen(reg.calls, 2)) + qt.Check(t, qt.Equals(reg.calls[0].body, ""), qt.Commentf("the claim never carries the organisation")) + qt.Check(t, qt.Equals(reg.calls[1].path, doorMemberships)) + qt.Check(t, qt.Equals(reg.calls[1].body, tc.wantBody)) + }) + } +} + // A machine member is asked about by its client id, which is its token subject. func TestAMachineMembersTokenNamesItsClientID(t *testing.T) { reg := newSignInRegister(t, map[string]func(w http.ResponseWriter){ @@ -193,7 +220,7 @@ func TestAMachineMembersTokenNamesItsClientID(t *testing.T) { r, _ := reg.resolver() inRequest(t, func(ctx *azugo.Context) { - _, err := r.Memberships(ctx, "svc:a-machine") + _, err := r.Memberships(ctx, "svc:a-machine", "") qt.Assert(t, qt.IsNil(err)) }) @@ -212,7 +239,7 @@ func TestAnAnswerAboutAnotherPersonIsRefused(t *testing.T) { r, _ := reg.resolver() inRequest(t, func(ctx *azugo.Context) { - got, err := r.Memberships(ctx, PersonKey(annaSub)) + got, err := r.Memberships(ctx, PersonKey(annaSub), "") qt.Check(t, qt.ErrorIs(err, ErrAnswerForAnotherSubject)) qt.Check(t, qt.IsNil(got)) }) @@ -227,7 +254,7 @@ func TestARefusalAtADoorFailsTheLookup(t *testing.T) { r, _ := reg.resolver() inRequest(t, func(ctx *azugo.Context) { - _, err := r.Memberships(ctx, PersonKey(annaSub)) + _, err := r.Memberships(ctx, PersonKey(annaSub), "") qt.Check(t, qt.ErrorMatches(err, `rolebyte: /api/v1/sign-in/claims answered 403`)) }) qt.Check(t, qt.HasLen(reg.calls, 1), qt.Commentf("the lookup is never asked after a refused claim")) @@ -274,7 +301,7 @@ func TestMembershipsDecodeTheOrganisationsName(t *testing.T) { r, _ := reg.resolver() inRequest(t, func(ctx *azugo.Context) { - got, err := r.Memberships(ctx, PersonKey(annaSub)) + got, err := r.Memberships(ctx, PersonKey(annaSub), "") qt.Assert(t, qt.IsNil(err)) qt.Assert(t, qt.HasLen(got, 1)) qt.Check(t, qt.Equals(got[0].TenantID, "t1")) @@ -305,7 +332,7 @@ func TestMembershipsDecodeTheHighOnlyScopes(t *testing.T) { r, _ := reg.resolver() inRequest(t, func(ctx *azugo.Context) { - got, err := r.Memberships(ctx, PersonKey(annaSub)) + got, err := r.Memberships(ctx, PersonKey(annaSub), "") qt.Assert(t, qt.IsNil(err)) qt.Assert(t, qt.HasLen(got, 1)) qt.Check(t, qt.DeepEquals(got[0].Scopes, []string{"a:b"})) diff --git a/routes/shared.go b/routes/shared.go index 0293a58..bf3ca0a 100644 --- a/routes/shared.go +++ b/routes/shared.go @@ -131,7 +131,7 @@ func (r *router) sharedWay(ctx *azugo.Context, req *authorizeRequest, sh *sessio // A person the token issue would refuse for want of a membership is not // answered silently: they get the page, and so a way to choose another. if resolver := r.ScopeResolver(); resolver != nil && r.Registry().MembershipRequired(req.clientID, true) { - ms, err := resolver.Memberships(ctx, rolebyte.PersonKey(sh.Subject)) + ms, err := resolver.Memberships(ctx, rolebyte.PersonKey(sh.Subject), "") if err != nil { return nil, refusedRegister } diff --git a/routes/token.go b/routes/token.go index c3930be..1c0dfef 100644 --- a/routes/token.go +++ b/routes/token.go @@ -80,7 +80,7 @@ func (r *router) userScopes(ctx *azugo.Context, sess *session.Session, clientID, // The register key of a person is their platform subject, typed — the // session always has one, whatever login method produced it. key := rolebyte.PersonKey(sess.Subject) - memberships, err := resolver.Memberships(ctx, key) + memberships, err := resolver.Memberships(ctx, key, registerCompany(tenantHint)) if err != nil { return r.registerUnavailable(ctx, key, err) } @@ -103,7 +103,7 @@ func (r *router) userScopes(ctx *azugo.Context, sess *session.Session, clientID, return r.registerUnavailable(ctx, key, err) } if admitted { - if memberships, err = resolver.Memberships(ctx, key); err != nil { + if memberships, err = resolver.Memberships(ctx, key, registerCompany(tenantHint)); err != nil { return r.registerUnavailable(ctx, key, err) } } @@ -212,6 +212,19 @@ func (r *router) registerUnavailable(ctx *azugo.Context, asked string, err error return membershipOutcome{}, false } +// registerCompany is the organisation the register is told a token is being +// issued for: the name given when it has the shape of an organisation id, and +// none otherwise. A name of any other shape matches no membership anyway, so the +// register is asked as for no organisation (it would refuse the name) and +// chooseMembership still compares the name as given. +func registerCompany(named string) string { + if personIDPattern.MatchString(named) { + return named + } + + return "" +} + // chooseMembership picks the membership a token is minted for: the named one // when a tenant was named (nil when the subject holds no membership there), // the only one when there is exactly one, and none — with the organisations @@ -619,7 +632,7 @@ func (r *router) serviceAccountScopes(ctx *azugo.Context, clientID, tenant strin // The register key of a service account is its own client id — the name // it authenticated with and carries as its token subject. - memberships, err := resolver.Memberships(ctx, clientID) + memberships, err := resolver.Memberships(ctx, clientID, registerCompany(tenant)) if err != nil { ctx.Log().Warn("membership resolve failed — refusing token issue: " + err.Error()) if errors.Is(err, rolebyte.ErrAnswerForAnotherSubject) { diff --git a/routes/token_memberships_test.go b/routes/token_memberships_test.go index 89c1532..c11885a 100644 --- a/routes/token_memberships_test.go +++ b/routes/token_memberships_test.go @@ -462,7 +462,7 @@ func TestAServiceAccountsAnswerListsNoOrganisations(t *testing.T) { // may ask it. type steadyRegister struct{ memberships []rolebyte.Membership } -func (s steadyRegister) Memberships(*azugo.Context, string) ([]rolebyte.Membership, error) { +func (s steadyRegister) Memberships(*azugo.Context, string, string) ([]rolebyte.Membership, error) { return s.memberships, nil } diff --git a/routes/token_register_company_test.go b/routes/token_register_company_test.go new file mode 100644 index 0000000..c324056 --- /dev/null +++ b/routes/token_register_company_test.go @@ -0,0 +1,91 @@ +package routes + +import ( + "testing" + + "github.com/go-quicktest/qt" + "github.com/valyala/fasthttp" + + "github.com/go-make-bytes/authbyte/rolebyte" +) + +// A sign-in that names an organisation tells the register which one the token +// is for; one that names none tells it none. +func TestASignInTellsTheRegisterTheOrganisationItNames(t *testing.T) { + two := []rolebyte.Membership{named(orgA, "Alpha Ltd", "a:a"), named(orgB, "Beta Ltd", "b:b")} + + for name, tc := range map[string]struct{ named, want string }{ + "names one": {orgA, orgA}, + "names none": {"", ""}, + } { + t.Run(name, func(t *testing.T) { + fake := &fakeResolver{memberships: two} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + _, status, body := exchanged(t, mem, e, tc.named) + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + qt.Check(t, qt.Equals(fake.askedTenant, tc.want)) + }) + } +} + +// An organisation named in the request that is not an organisation id is never +// passed to the register, which would refuse it: the answer is the one a name no +// membership matches always got, and the register is called with no company. The +// same holds for a service account's request. +func TestANameThatIsNotAnOrganisationIdIsNotPassedToTheRegister(t *testing.T) { + two := []rolebyte.Membership{named(orgA, "Alpha Ltd", "a:a"), named(orgB, "Beta Ltd", "b:b")} + + t.Run("sign-in", func(t *testing.T) { + fake := &fakeResolver{memberships: two} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + _, status, body := exchanged(t, mem, e, "not-a-company") + qt.Check(t, qt.Equals(status, fasthttp.StatusForbidden), qt.Commentf("%s", body["_raw"])) + qt.Check(t, qt.StringContains(body["_raw"].(string), "err:membership:notMember")) + qt.Check(t, qt.Equals(fake.asked, "sub:"+testPersonSub(5)), qt.Commentf("the register was asked")) + qt.Check(t, qt.Equals(fake.askedTenant, "")) + }) + + t.Run("service account", func(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{member(orgA, "signing-requests:write")}} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/service?tenant=not-a-company&allowed=signing-requests:write") + qt.Check(t, qt.Equals(status, fasthttp.StatusForbidden), qt.Commentf("%s", body)) + qt.Check(t, qt.StringContains(body, "err:membership:notMember")) + qt.Check(t, qt.Equals(fake.asked, "svc:acme-dms"), qt.Commentf("the register was asked")) + qt.Check(t, qt.Equals(fake.askedTenant, "")) + }) +} + +// A refresh tells the register the organisation its session is in. +func TestARefreshTellsTheRegisterTheOrganisationOfItsSession(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{named(orgA, "Alpha Ltd", "a:a")}} + app, mem := signInApp(t, withRegister(fake)) + e := newEdge(t, app) + + _, status, body := exchanged(t, mem, e, "") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + qt.Check(t, qt.Equals(fake.askedTenant, ""), qt.Commentf("the sign-in named none and the person is in one")) + refresh, _ := body["refresh_token"].(string) + + fake.askedTenant = "unset" + status, body = e.refresh(refresh, "product-spa") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body["_raw"])) + qt.Check(t, qt.Equals(fake.askedTenant, orgA)) +} + +// A service account's token for an organisation tells the register that one. +func TestAServiceAccountsTokenTellsTheRegisterTheOrganisationItAsksFor(t *testing.T) { + fake := &fakeResolver{memberships: []rolebyte.Membership{ + member(orgA, "signing-requests:write"), + }} + app := scopesApp(t, fake) + + status, body := get(t, app, "/testonly/service?tenant="+orgA+"&allowed=signing-requests:write") + qt.Assert(t, qt.Equals(status, fasthttp.StatusOK), qt.Commentf("%s", body)) + qt.Check(t, qt.Equals(fake.askedTenant, orgA)) +} diff --git a/routes/token_rolebyte_test.go b/routes/token_rolebyte_test.go index 8460846..7b697c1 100644 --- a/routes/token_rolebyte_test.go +++ b/routes/token_rolebyte_test.go @@ -77,6 +77,7 @@ type fakeResolver struct { memberships []rolebyte.Membership err error asked string // the subject key the seam passed down ("" = never asked) + askedTenant string // the organisation the seam passed down ("" = none named) // The admission door: what it answers, what it was asked, and what the // register answers AFTER a successful admission. @@ -100,8 +101,9 @@ func (f *fakeResolver) Assistants(_ *azugo.Context, subjectKey string) ([]roleby return f.assistants[subjectKey], nil } -func (f *fakeResolver) Memberships(_ *azugo.Context, subjectKey string) ([]rolebyte.Membership, error) { +func (f *fakeResolver) Memberships(_ *azugo.Context, subjectKey, tenant string) ([]rolebyte.Membership, error) { f.asked = subjectKey + f.askedTenant = tenant if f.err != nil { return nil, f.err } From 5597d0225f9bc48fef7583bd3bb2668e2a1a421b Mon Sep 17 00:00:00 2001 From: GatisB Date: Tue, 17 Nov 2026 17:37:25 +0000 Subject: [PATCH 6/6] Move to azugo v0.50.2 and Go 1.27.4 Signed-off-by: GatisB --- CHANGELOG.md | 7 +++ go.mod | 46 +++++++++--------- go.sum | 100 +++++++++++++++++++-------------------- routes/bodylimit_test.go | 47 ++++++++++++++++++ routes/clientauth.go | 8 +++- routes/persons.go | 9 +++- routes/token.go | 51 ++++++++++++++++---- 7 files changed, 185 insertions(+), 83 deletions(-) create mode 100644 routes/bodylimit_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 894d46d..02c17e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ runs the service or integrates against it. ## v0.13.0 +### Changed + +- **The service runs on Go 1.27.4 and azugo v0.50.2.** Request bodies read through the framework (the token and + refresh forms, and the person-lines read) are held to its limit: a body over 4 MiB answers 413 in the problem + envelope, or the limit `SERVER_MAX_REQUEST_BODY_SIZE` sets. A malformed multipart body answers 400. No route + raises its own limit; every body these routes take is small. + ### Added - **The token answer of a person in several organisations lists them by name.** When the membership register diff --git a/go.mod b/go.mod index 2d1ad4c..dffd67c 100644 --- a/go.mod +++ b/go.mod @@ -3,30 +3,30 @@ module github.com/go-make-bytes/authbyte go 1.27.4 require ( - azugo.io/azugo v0.40.2 - azugo.io/core v0.40.1 - azugo.io/opentelemetry v0.40.1 - github.com/gmb-lib/go-authbyte v0.35.0 - github.com/gmb-lib/go-gdpr-audit v1.1.8 - github.com/gmb-lib/go-platform-kit v1.11.6 - github.com/gmb-lib/go-sec-events v1.2.3 - github.com/go-jose/go-jose/v4 v4.1.7 + azugo.io/azugo v0.50.2 + azugo.io/core v0.50.1 + azugo.io/opentelemetry v0.50.0 + github.com/gmb-lib/go-authbyte v0.46.0 + github.com/gmb-lib/go-gdpr-audit v1.2.0 + github.com/gmb-lib/go-platform-kit v1.13.0 + github.com/gmb-lib/go-sec-events v1.3.0 + github.com/go-jose/go-jose/v4 v4.1.9 github.com/go-quicktest/qt v1.102.0 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/jackc/pgx/v5 v5.12.0 github.com/spf13/cobra v1.10.2 github.com/spf13/viper v1.21.0 - github.com/valkey-io/valkey-go v1.0.79 - github.com/valyala/fasthttp v1.77.0 + github.com/valkey-io/valkey-go v1.0.80 + github.com/valyala/fasthttp v1.79.0 go.opentelemetry.io/otel/sdk v1.47.0 go.uber.org/zap v1.28.0 - go.yaml.in/yaml/v3 v3.0.5 + go.yaml.in/yaml/v3 v3.0.6 ) require ( - github.com/VictoriaMetrics/metrics v1.44.1 // indirect + github.com/VictoriaMetrics/metrics v1.45.0 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect - github.com/cenkalti/backoff/v7 v7.0.1 // indirect + github.com/cenkalti/backoff/v7 v7.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/dgraph-io/ristretto/v2 v2.4.2 // indirect github.com/dustin/go-humanize v1.1.0 // indirect @@ -37,17 +37,17 @@ require ( github.com/go-logr/stdr v1.2.2 // indirect github.com/go-playground/locales v0.14.2 // indirect github.com/go-playground/universal-translator v0.18.2 // indirect - github.com/go-playground/validator/v10 v10.30.5 // indirect + github.com/go-playground/validator/v10 v10.30.6 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/goccy/go-json v0.12.0 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect - github.com/klauspost/compress v1.20.3 // indirect + github.com/klauspost/compress v1.20.4 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/lafriks/http2 v0.6.1 // indirect @@ -64,7 +64,7 @@ require ( github.com/sagikazarmark/locafero v0.12.0 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect - github.com/spf13/pflag v1.0.10 // indirect + github.com/spf13/pflag v1.1.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fastrand v1.1.0 // indirect @@ -88,13 +88,13 @@ require ( go.opentelemetry.io/proto/otlp v1.11.1 // indirect go.uber.org/atomic v1.12.0 // indirect go.uber.org/multierr v1.11.0 // indirect - golang.org/x/crypto v0.58.0 // indirect + golang.org/x/crypto v0.59.0 // indirect golang.org/x/net v0.62.0 // indirect - golang.org/x/sync v0.24.0 // indirect - golang.org/x/sys v0.49.0 // indirect - golang.org/x/text v0.43.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20261026165753-2ffab32bce7e // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e // indirect + golang.org/x/sync v0.25.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/text v0.44.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20261116203732-fd2c7689a808 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20261116203732-fd2c7689a808 // indirect google.golang.org/grpc v1.85.0 // indirect google.golang.org/protobuf v1.36.12 // indirect ) diff --git a/go.sum b/go.sum index c1ace2a..64edd28 100644 --- a/go.sum +++ b/go.sum @@ -1,19 +1,19 @@ -azugo.io/azugo v0.40.2 h1:n3r/DZPbDTfnuPGW8YqlidghK763rYiggTgvtI5FwOQ= -azugo.io/azugo v0.40.2/go.mod h1:mV1dMKr4wLfY04IteOMxSHv9E8V96nIWJJGZVgks8H4= -azugo.io/core v0.40.1 h1:DVu9TIKsU4r9/idB/MyvYSgJRgqaUI9Pi71rVeJ8bKU= -azugo.io/core v0.40.1/go.mod h1:JuE4GzlWtv4lN+GTGHOLWPCYkJx3+DtcCdDGcyUrIaI= -azugo.io/opentelemetry v0.40.1 h1:anoXeH14swnEyyFZkGgeacTQWuhph4CZ0E0YCpcqNMs= -azugo.io/opentelemetry v0.40.1/go.mod h1:PdZEq9p7dElEOt91kJY5RVdWRhil4HDJhv5zqfefLPw= -github.com/VictoriaMetrics/metrics v1.44.1 h1:OMyGrMkhI3hnq+IpJ1gZK9VhXcsOjUX1CoOFv//bJ0I= -github.com/VictoriaMetrics/metrics v1.44.1/go.mod h1:xDM82ULLYCYdFRgQ2JBxi8Uf1+8En1So9YUwlGTOqTc= +azugo.io/azugo v0.50.2 h1:S0FnHGFwZ0XuBRBQM/Y0rhjgMq/+hZZcY1KX1eg/eMY= +azugo.io/azugo v0.50.2/go.mod h1:MP3dy12pZRHFXmyDPL0lgghARxFXMx48JqPsDeOf3lc= +azugo.io/core v0.50.1 h1:3P6qsow3l2pjQAFSuKsN0ET6R5ZgXaZRzvrKror5PWQ= +azugo.io/core v0.50.1/go.mod h1:5dTIUEN2nI5TfLhcRWje8sp6NbIWyKbOkh4HbfnPQck= +azugo.io/opentelemetry v0.50.0 h1:IseD0yQXtqycBW7jmjls9YKNZ6cS75OMBJt0R7h+Snw= +azugo.io/opentelemetry v0.50.0/go.mod h1:Ic0TJvyk03RQcdvdA6LUubkyk9lQVY0DAfJbKRUy2zU= +github.com/VictoriaMetrics/metrics v1.45.0 h1:Tv8dZRAjkO90rBTxYrWOHUWFBHsAKdKcZYmS/Wbo2EU= +github.com/VictoriaMetrics/metrics v1.45.0/go.mod h1:xDM82ULLYCYdFRgQ2JBxi8Uf1+8En1So9YUwlGTOqTc= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= -github.com/cenkalti/backoff/v7 v7.0.1 h1:+ulHti5s1d9QnfyOnLWVmQ/SaZ+TJQF9OdOI0i9BGZI= -github.com/cenkalti/backoff/v7 v7.0.1/go.mod h1:qcKBGwsu4hpxHtQ8tWYsQ+ifzx2+sS+Xx/3jfe30lI8= +github.com/cenkalti/backoff/v7 v7.0.3 h1:oJlXCmDgfNcGYViwioz1cZ1kHebejP4OLfJ/gqMQVWA= +github.com/cenkalti/backoff/v7 v7.0.3/go.mod h1:qcKBGwsu4hpxHtQ8tWYsQ+ifzx2+sS+Xx/3jfe30lI8= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= @@ -33,16 +33,16 @@ github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx5 github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= -github.com/gmb-lib/go-authbyte v0.35.0 h1:EXDortebh2KhZDYj9Xm86AgH9F67jIgJL9lROSFd29I= -github.com/gmb-lib/go-authbyte v0.35.0/go.mod h1:IZfR8kVt5ItxT2QrHGebBVGkK5sOvJjqCyGOX9+ynMw= -github.com/gmb-lib/go-gdpr-audit v1.1.8 h1:l/ieRtPo/gj9Qhj++lxZjUK+D95hJRJUFDIpYiFjSi8= -github.com/gmb-lib/go-gdpr-audit v1.1.8/go.mod h1:lNaOvzV5EqHU0GmKuZ9wuSKl5OxKzJrovKTeaVseBXU= -github.com/gmb-lib/go-platform-kit v1.11.6 h1:yxBSvUzbZ3tvikQKtUPj3gnRq5wJBEz7kGVICxg6LNk= -github.com/gmb-lib/go-platform-kit v1.11.6/go.mod h1:Gz/r7sVGdAQ96BUzcDPV7rI88OqYQpWkkRFrykARexk= -github.com/gmb-lib/go-sec-events v1.2.3 h1:zcu4EoqdDryZdp4Ildc9y/iaIUjtEAOIOXDl/okEx9g= -github.com/gmb-lib/go-sec-events v1.2.3/go.mod h1:9fiRjZ2lYGfeYJ1YC42URE9DZBKg+BWXk5jNOgnRXp8= -github.com/go-jose/go-jose/v4 v4.1.7 h1:Nac/98uT5LPkfbiFuYa8ktf62a2VxwQ4xbq1GK8pV5E= -github.com/go-jose/go-jose/v4 v4.1.7/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/gmb-lib/go-authbyte v0.46.0 h1:T1c0Fx/gsf8hjI3ExI48o6G+c3royNzmdJctn5kyI2I= +github.com/gmb-lib/go-authbyte v0.46.0/go.mod h1:QZhlLpFzug6/gDRHRf3rUi3Xpr/fI0SkhsKxRkJDyPg= +github.com/gmb-lib/go-gdpr-audit v1.2.0 h1:Rt5LmhxOxIJZf5Nz+Va1sHumwzLB3R1fiRmlrmDmkKI= +github.com/gmb-lib/go-gdpr-audit v1.2.0/go.mod h1:KrQIKXTZ/LBw935XlKNATAM8jWjKtuBp0O6od200WPo= +github.com/gmb-lib/go-platform-kit v1.13.0 h1:DeoUXL4Eq309u9Ufhx9PleW/qMmkR8OXQoUHRcuAkYo= +github.com/gmb-lib/go-platform-kit v1.13.0/go.mod h1:FtcG128HmBeFcaO/+SSzxU9ZpkB52rhZFLJIYH2R9CI= +github.com/gmb-lib/go-sec-events v1.3.0 h1:ttnPVEHo54994amFuA9ppasfO54GMOiuUWKTfPy3+Vc= +github.com/gmb-lib/go-sec-events v1.3.0/go.mod h1:XS5KG84UYPrs/JU+ejo/E0mA2Zw1iqlQ0g+NQYd4+y0= +github.com/go-jose/go-jose/v4 v4.1.9 h1:pKfeQkig1NmgK4hJrZYXLEYURXfoJB61Larw0uIW4gY= +github.com/go-jose/go-jose/v4 v4.1.9/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -54,8 +54,8 @@ github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9 github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= -github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4= -github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ= +github.com/go-playground/validator/v10 v10.30.6 h1:E+mymlPNRzAMNz1FShrRvLeGWcprF5w305eLLgWieuo= +github.com/go-playground/validator/v10 v10.30.6/go.mod h1:jPLL8SKCXGe/g87QmEyNw3NO28nmGt5GCnZnufm7rj4= github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474= github.com/go-quicktest/qt v1.102.0/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI= github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= @@ -70,8 +70,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0 h1:5T5Ns3kMpWr+z3s5ZA0e7ljVyWNVNxK76sHPAxi5D1k= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0/go.mod h1:oWNYw09cH8wl8fFgC5hKlBLxR4XfKy2KQpP8MJjeCcc= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= @@ -82,8 +82,8 @@ github.com/jackc/pgx/v5 v5.12.0 h1:hWwax8YiGT0YiN50U1oIDn5kgR7KC2tG3rmavwpPkxY= github.com/jackc/pgx/v5 v5.12.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= -github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= -github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= +github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -104,8 +104,8 @@ github.com/molecule-man/go-brrr v1.3.1 h1:EwaJUzRIlp/dFmIpzq4J17CA5Zi5OHo2vOGmu0 github.com/molecule-man/go-brrr v1.3.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4= github.com/oklog/ulid/v2 v2.1.2 h1:IEclFb9JNvzYA6MW2SCxbLzcHTVsfqm3PrqGQJH5zec= github.com/oklog/ulid/v2 v2.1.2/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= -github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I= -github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg= +github.com/onsi/gomega v1.44.0 h1:eAiGl3Pw5jz5GQdDff0BcxYpAX1JxW8xD7mFUuwNfZQ= +github.com/onsi/gomega v1.44.0/go.mod h1:e/C2HwaZ1DhvjzXXuFhcR7hY7Sh9pl7MmoWKEjzwcdA= github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= @@ -128,8 +128,8 @@ github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qq github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= -github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag= +github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -139,12 +139,12 @@ github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWD github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= -github.com/valkey-io/valkey-go v1.0.79 h1:dryzYka/oOkSMOcNmOTjQI8zfu/4bUzDZNnFW9NlqNM= -github.com/valkey-io/valkey-go v1.0.79/go.mod h1:gvC/r2m3eW4Hbj0YnjogTzNtFdPSM/D+NCqen+5OABM= +github.com/valkey-io/valkey-go v1.0.80 h1:nyjeE1W9RpUU1KcsApBLlzjisZMVmgTQBGmlsuC0vtE= +github.com/valkey-io/valkey-go v1.0.80/go.mod h1:9M4jE0WGI4fBPijXwbmnO3T7hu5UCjI9ABx+jMCvekQ= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasthttp v1.77.0 h1:6mxBJdHabRmU4Cmw79Uqhgvjzsp6pjOaQk2t8COflzo= -github.com/valyala/fasthttp v1.77.0/go.mod h1:m8oTPC8riDDky07invpl+Gz3RixnAN5BbwyUuVB5H2o= +github.com/valyala/fasthttp v1.79.0 h1:32ur91W4kWG+1s6x3oDlP8/KNmjlZZlUzSSC4p9LSWE= +github.com/valyala/fasthttp v1.79.0/go.mod h1:NQN+PlgP93+JRPnCiApN5XwnI24oMQf8kuzrxtsTy9A= github.com/valyala/fastrand v1.1.0 h1:f+5HkLW4rsgzdNoleUOB69hyT9IlD2ZQh9GyDMfb5G8= github.com/valyala/fastrand v1.1.0/go.mod h1:HWqCzkrkg6QXT8V2EXWvXCoow7vLwOFN002oeRzjapQ= github.com/valyala/histogram v1.2.0 h1:wyYGAZZt3CpwUiIb9AU/Zbllg1llXyrtApRS815OLoQ= @@ -200,26 +200,26 @@ go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN8 go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= -go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= -go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= -golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= -golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= +go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= -golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= -golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= -golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= -golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= -golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= -golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= -golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a h1:Yqozs0FNPRoPGS4hNGlrNwRENWr5H5nVG9sN/f+5640= +golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/genproto/googleapis/api v0.0.0-20261026165753-2ffab32bce7e h1:e789sLZjeTdc02ZCQGTSzHOu0fR73+dwPQVKUp67Z88= -google.golang.org/genproto/googleapis/api v0.0.0-20261026165753-2ffab32bce7e/go.mod h1:vHV3wJM9WZyfV7GyB+OQGq5dWVrFwCDxapPK4WlRD88= -google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e h1:w3fy/G8OrJHYexn+u5y7hFyc8YRRIr7DCevtIOwAcGY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20261026165753-2ffab32bce7e/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/genproto/googleapis/api v0.0.0-20261116203732-fd2c7689a808 h1:138uiCpAaz8IK/8xoJcj2MQUWL5MMtaV7ofVoQJpuY8= +google.golang.org/genproto/googleapis/api v0.0.0-20261116203732-fd2c7689a808/go.mod h1:Q/ieadaUFs1Xg9kiCENqJcpZMo0aTO4nUCWroI7gAdQ= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261116203732-fd2c7689a808 h1:fTdQSdJnh58Hq9AG3truAGfWr7VEZ3tCU3DE5kDnTDE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261116203732-fd2c7689a808/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= diff --git a/routes/bodylimit_test.go b/routes/bodylimit_test.go new file mode 100644 index 0000000..17220b1 --- /dev/null +++ b/routes/bodylimit_test.go @@ -0,0 +1,47 @@ +package routes + +import ( + "net/url" + "strings" + "testing" + + "github.com/go-quicktest/qt" + "github.com/valyala/fasthttp" +) + +// overLimit is larger than the framework's default request body limit (4 MiB). +const overLimit = 4<<20 + 1024 + +// A form body over the framework's limit is refused with 413 before any +// grant is looked at. +func TestATokenFormOverTheBodyLimitIsRefusedWith413(t *testing.T) { + app, _ := signInApp(t) + e := newEdge(t, app) + + status, _ := e.post("/token", url.Values{ + "grant_type": {"authorization_code"}, + "code": {strings.Repeat("a", overLimit)}, + }) + qt.Check(t, qt.Equals(status, fasthttp.StatusRequestEntityTooLarge)) +} + +// A form body well under the limit is still read as before. +func TestATokenFormUnderTheBodyLimitIsRead(t *testing.T) { + app, _ := signInApp(t) + e := newEdge(t, app) + + status, _ := e.post("/token", url.Values{ + "grant_type": {"authorization_code"}, + "code": {strings.Repeat("a", 1<<10)}, + }) + qt.Check(t, qt.Not(qt.Equals(status, fasthttp.StatusRequestEntityTooLarge))) +} + +// The person-lines read refuses a JSON body over the limit with 413. +func TestPersonLinesBodyOverTheLimitIsRefusedWith413(t *testing.T) { + app := peopleApp(t, &fakePeople{}) + + status, _, _ := send(t, app, linesService, fasthttp.MethodPost, "/testonly/lines", + `{"subjects":["`+strings.Repeat("a", overLimit)+`"]}`) + qt.Check(t, qt.Equals(status, fasthttp.StatusRequestEntityTooLarge)) +} diff --git a/routes/clientauth.go b/routes/clientauth.go index ef60625..cc34942 100644 --- a/routes/clientauth.go +++ b/routes/clientauth.go @@ -26,7 +26,13 @@ func clientSecret(ctx *azugo.Context, clientID string) (secret string, presented return "", false, false } - form := ctx.Form.StringOptional("client_secret") + form, err := ctx.Form.StringOptional("client_secret") + if err != nil { + ctx.Error(err) + + return "", false, false + } + if hasBasic && form != nil { ctx.Error(azugo.ParamInvalidError{Name: "client_secret", Tag: "one-method"}) diff --git a/routes/persons.go b/routes/persons.go index da21ca6..2ab8700 100644 --- a/routes/persons.go +++ b/routes/persons.go @@ -143,7 +143,14 @@ func (r *router) personLines(ctx *azugo.Context) { } var req personLinesRequest - if err := json.Unmarshal(ctx.Body.Bytes(), &req); err != nil || len(req.Subjects) == 0 { + body, readErr := ctx.Body.Bytes() + if readErr != nil { + ctx.Error(readErr) + + return + } + + if err := json.Unmarshal(body, &req); err != nil || len(req.Subjects) == 0 { invalidPersons(ctx, "subjects must be a non-empty list of person subjects") return diff --git a/routes/token.go b/routes/token.go index 1c0dfef..44004e0 100644 --- a/routes/token.go +++ b/routes/token.go @@ -300,7 +300,14 @@ func (r *router) token(ctx *azugo.Context) { // An AI app holds no proof-of-possession key: its code exchange and its // refreshes are answered without one, and its tokens are bound to none. if grant == "authorization_code" || grant == "refresh_token" { - if id := ctx.Form.StringOptional("client_id"); id != nil { + id, idErr := ctx.Form.StringOptional("client_id") + if idErr != nil { + ctx.Error(idErr) + + return + } + + if id != nil { if app, ok := r.Registry().AIApp(*id); ok { r.grantForApp(ctx, grant, app) @@ -556,14 +563,28 @@ func (r *router) grantClientCredentials(ctx *azugo.Context, thumbprint string) { return } + scopeValue, err := ctx.Form.StringOptional("scope") + if err != nil { + ctx.Error(err) + + return + } + var requested []string - if s := ctx.Form.StringOptional("scope"); s != nil { - requested = registry.ParseScopeString(*s) + if scopeValue != nil { + requested = registry.ParseScopeString(*scopeValue) + } + + tenantValue, err := ctx.Form.StringOptional("tenant") + if err != nil { + ctx.Error(err) + + return } tenant := "" - if t := ctx.Form.StringOptional("tenant"); t != nil { - tenant = *t + if tenantValue != nil { + tenant = *tenantValue } if _, err := r.Registry().Authenticate(clientID, secret); err != nil { @@ -787,15 +808,29 @@ func (r *router) grantTokenExchange(ctx *azugo.Context, thumbprint string) { // subject_token_type, when supplied, must name an access token — the only // token type the platform exchanges. - if st := ctx.Form.StringOptional("subject_token_type"); st != nil && *st != tokenTypeAccessToken { + st, err := ctx.Form.StringOptional("subject_token_type") + if err != nil { + ctx.Error(err) + + return + } + + if st != nil && *st != tokenTypeAccessToken { ctx.Error(azugo.ParamInvalidError{Name: "subject_token_type", Tag: "eq=" + tokenTypeAccessToken}) return } + scopeValue, err := ctx.Form.StringOptional("scope") + if err != nil { + ctx.Error(err) + + return + } + var requested []string - if s := ctx.Form.StringOptional("scope"); s != nil { - requested = registry.ParseScopeString(*s) + if scopeValue != nil { + requested = registry.ParseScopeString(*scopeValue) } // Authenticate the requesting (delegating) client.