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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1045,9 +1045,9 @@ linters:
- github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server$
- github.com/stacklok/mecatl/internal/identitybroker/adapter/authserverclient$
- github.com/stacklok/mecatl/internal/testutil/identityharness$
# The identity harness stands in for the IdP, AS-1, AS-2, and the
# gateway; it never imports the code under test, so a broker bug
# cannot also bend the stand-in. Its external tests import the harness
# The identity harness stands in for the IdP and the gateway; it
# never imports the code under test, so a broker bug cannot also bend
# the stand-in. Its external tests import the harness
# itself, the one Mecatl package allowed.
internal-testutil-identityharness:
list-mode: lax
Expand Down Expand Up @@ -1287,6 +1287,13 @@ linters:
msg: 'global slog is banned in engine/ and internal/: only cmd/ mains may install a slog default (the third-party-slog bridge). Everything else must take a port.Diagnostics.'
- pattern: 'slog\.(Info|Warn|Debug|Error)(Context)?\b'
msg: 'package-level slog.* is banned in engine/ and internal/: log through the injected port.Diagnostics seam, not the global logger.'
# as1server.Server.RevokeGrant revokes in AS-1's storage, past AS-1's
# handler, client authentication, and ownership checks. It exists so
# tests can see AS-1 answer revoked; production revokes through
# AS-1's RFC 7009 route (stacklok/toolhive#6966). Tests are
# excluded below.
- pattern: '\.RevokeGrant\b'
msg: 'RevokeGrant is test-only: it bypasses AS-1''s handler and client authentication. Production revokes through AS-1''s RFC 7009 route (stacklok/toolhive#6966).'
goconst:
ignore-tests: true
min-occurrences: 5
Expand Down Expand Up @@ -1450,9 +1457,11 @@ linters:
# redirects the default to a file — so they MUST be allowed
# slog.Default/SetDefault. The ban exists to keep the engine and the adapters
# on the injected port.Diagnostics seam, not to police the mains.
# The text match keeps the RevokeGrant ban in force in cmd/.
- linters:
- forbidigo
path: (^|.*/)cmd/
text: slog
# Test files may name the banned patterns in literals/messages (e.g. the guard
# test asserting the rule bites, or doc-comments referencing slog.Warn).
- linters:
Expand Down
243 changes: 91 additions & 152 deletions cmd/mecak8s/identity_broker_harness_test.go

Large diffs are not rendered by default.

53 changes: 48 additions & 5 deletions cmd/mecak8s/identity_broker_real_as1_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ import (
// and the real AS-1, built by the test with the harness IdP as its upstream,
// as both the issuer of API access tokens and the authorization server
// session open converts them at. Once a broker session's hard expiry passes,
// the session is closed, and a new sign-in opens a new one. AS-1 stamps a grant's expiry with wall time, so
// the session is closed, and a new sign-in opens a new one, for a session and
// for its fork alike. AS-1 stamps a grant's expiry with wall time, so
// the test moves only the broker's clock past it, observes the close through
// calls that do not reach AS-1, and moves the clock back before a new sign-in
// reopens the session.
Expand Down Expand Up @@ -72,19 +73,42 @@ func TestIdentityBrokerAgainstRealAS1(t *testing.T) {
if !ok || bobsExpiring.Owner != bobCompany || !bobsExpiring.HoldsRefreshToken || a.Faults.Conversions() != 2 {
t.Fatalf("Bob's broker session = %+v, %v after %d conversions; want his holding a refresh token", bobsExpiring, ok, a.Faults.Conversions())
}
registerMain := func(brokerSession string) (identitybroker.Registration, error) {
// Alice forks her session with a new sign-in; the fork gets its own
// broker session, which converts that sign-in.
status, body := apiCall(t, http.MethodPost, api+"/v1/sessions/"+aliceID+"/fork", a.SignIn(t, as1servertest.SignIn{User: identityharness.Alice}).Value(), "{}")
var forked struct {
ID string `json:"session_id"`
}
if status != http.StatusCreated && status != http.StatusOK || json.Unmarshal([]byte(body), &forked) != nil || forked.ID == "" {
t.Fatalf("Alice forks her session: status %d: %s", status, body)
}
forkExpiring, ok := findBrokerSession(forked.ID)
if !ok || forkExpiring.ID == expiring.ID || forkExpiring.Owner != aliceCompany || !forkExpiring.HoldsRefreshToken || a.Faults.Conversions() != 3 {
t.Fatalf("the fork's broker session = %+v, %v after %d conversions; want its own holding a refresh token", forkExpiring, ok, a.Faults.Conversions())
}
register := func(host string, s identitybroker.Session, brokerSession string) (identitybroker.Registration, error) {
return built.IdentityBroker.RegisterAgent(t.Context(), identitybroker.RegisterAgentRequest{
SessionID: brokerSession, HostSessionID: aliceID, Owner: aliceCompany, Incarnation: expiring.Incarnation,
SessionID: brokerSession, HostSessionID: host, Owner: aliceCompany, Incarnation: s.Incarnation,
Definition: identitybroker.DefinitionRef{Source: "system", Name: "main"},
})
}
registerMain := func(brokerSession string) (identitybroker.Registration, error) {
return register(aliceID, expiring, brokerSession)
}
registerForkMain := func(brokerSession string) (identitybroker.Registration, error) {
return register(forked.ID, forkExpiring, brokerSession)
}
before, err := registerMain(expiring.ID)
if err != nil {
t.Fatalf("register Alice's main agent: %v", err)
}
forkBefore, err := registerForkMain(forkExpiring.ID)
if err != nil {
t.Fatalf("register the fork's main agent: %v", err)
}

// Hard expiry: AS-1 granted at most its configured maximum, so moving the
// broker past it closes both sessions. (The broker's SessionGrant is not
// broker past it closes every session. (The broker's SessionGrant is not
// reachable outside its package.)
requests := len(a.Faults.Requests())
clockOffset.Store(int64(as1servertest.IDJAGMaxLifetime + time.Minute))
Expand All @@ -104,6 +128,12 @@ func TestIdentityBrokerAgainstRealAS1(t *testing.T) {
if s, ok := findBrokerSession(bobID); ok {
t.Errorf("Bob's expired broker session is still found: %+v", s)
}
if _, err := registerForkMain(forkExpiring.ID); !errors.Is(err, closed) {
t.Errorf("register in the fork's expired broker session = %v, want %v", err, closed)
}
if s, ok := findBrokerSession(forked.ID); ok {
t.Errorf("the fork's expired broker session is still found: %+v", s)
}
if n := len(a.Faults.Requests()); n != requests {
t.Fatalf("observing the close sent AS-1 %d requests, want none", n-requests)
}
Expand All @@ -115,14 +145,27 @@ func TestIdentityBrokerAgainstRealAS1(t *testing.T) {
t.Fatalf("Alice prompts her session after its broker session expired: status %d: %s", status, body)
}
reopened, ok := findBrokerSession(aliceID)
if !ok || reopened.ID == expiring.ID || reopened.Owner != aliceCompany || !reopened.HoldsRefreshToken || a.Faults.Conversions() != 3 {
if !ok || reopened.ID == expiring.ID || reopened.Owner != aliceCompany || !reopened.HoldsRefreshToken || a.Faults.Conversions() != 4 {
t.Fatalf("Alice's broker session after expiry = %+v, %v after %d conversions; want a new one holding the new sign-in's refresh token", reopened, ok, a.Faults.Conversions())
}
// The 200 means the prompt's run entry registered the main agent in the
// new broker session; registering again here returns its agent.
if after, err := registerMain(reopened.ID); err != nil || after.Agent != before.Agent {
t.Errorf("register in the new broker session = %+v, %v; want agent %+v", after.Agent, err, before.Agent)
}
// The fork reopens the same way, in a broker session of its own.
forkFresh := a.SignIn(t, as1servertest.SignIn{User: identityharness.Alice}).Value()
if status, body := apiCall(t, http.MethodPost, api+"/v1/sessions/"+forked.ID+"/prompt", forkFresh, `{"text":"after expiry"}`); status != http.StatusOK {
t.Fatalf("Alice prompts her fork after its broker session expired: status %d: %s", status, body)
}
forkReopened, ok := findBrokerSession(forked.ID)
if !ok || forkReopened.ID == forkExpiring.ID || forkReopened.ID == reopened.ID || forkReopened.Owner != aliceCompany ||
!forkReopened.HoldsRefreshToken || a.Faults.Conversions() != 5 {
t.Fatalf("the fork's broker session after expiry = %+v, %v after %d conversions; want a new one of its own holding the new sign-in's refresh token", forkReopened, ok, a.Faults.Conversions())
}
if after, err := registerForkMain(forkReopened.ID); err != nil || after.Agent != forkBefore.Agent {
t.Errorf("register in the fork's new broker session = %+v, %v; want agent %+v", after.Agent, err, forkBefore.Agent)
}
// A tokenless open after the expiry pairs a new session that holds no
// refresh token.
bobsReopened, err := built.IdentityBroker.OpenSession(t.Context(), identitybroker.OpenSessionRequest{
Expand Down
34 changes: 21 additions & 13 deletions cmd/mecak8s/tui_sign_in_harness_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import (
"github.com/stacklok/mecatl/internal/adapter/clientauth"
"github.com/stacklok/mecatl/internal/adapter/credentialstore"
"github.com/stacklok/mecatl/internal/identitybroker"
"github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server"
"github.com/stacklok/mecatl/internal/identitybroker/adapter/as1server/as1servertest"
"github.com/stacklok/mecatl/internal/testutil/identityharness"
"github.com/stacklok/mecatl/mcp/oauthlogin"
)
Expand Down Expand Up @@ -130,15 +132,18 @@ func (r *resourceRecorder) grantsWithResource(want string) map[string]int {
}

// TestTUISignsInAtAS1AndOpensEachSessionWithAFreshToken signs the TUI's real
// client code in at the offline AS-1 (authorization code + PKCE, RFC 8707
// resource as mecak8s's protected-resource metadata asks), then drives mecak8s over gRPC through the TUI client with the
// clientauth refresh source: each session create carries a freshly refreshed
// token with its own jti, and mecak8s accepts each and opens a broker session
// owned by the signed-in company identity.
// client code in at the real AS-1, run outside mecak8s and named by
// --oidc-issuer (authorization code + PKCE, RFC 8707 resource as mecak8s's
// protected-resource metadata asks), then drives mecak8s over gRPC through
// the TUI client with the clientauth refresh source: each session create
// carries a freshly refreshed token with its own jti, and mecak8s accepts
// each and opens a broker session owned by the signed-in company identity.
// TestHostedAS1SignsTheTUIIn does the same with the AS-1 mecak8s hosts.
func TestTUISignsInAtAS1AndOpensEachSessionWithAFreshToken(t *testing.T) {
h := identityharness.New(t, identityharness.Options{Clients: []identityharness.Client{
{ID: identityharness.DefaultClientID, RedirectURIs: []string{oauthlogin.ExactRedirectURL}},
}})
h := identityharness.New(t, identityharness.Options{})
a := as1servertest.Start(t, h, func(c *as1server.Config, _ *as1server.DelegateClient) {
c.PublicClients = append(c.PublicClients, as1server.PublicClient{ID: identityharness.DefaultClientID, RedirectURIs: []string{oauthlogin.ExactRedirectURL}})
})
cfg, err := parseFlags([]string{
"--mock",
"--enable-identity-broker", "--no-shell",
Expand All @@ -147,8 +152,8 @@ func TestTUISignsInAtAS1AndOpensEachSessionWithAFreshToken(t *testing.T) {
"--http-addr", freeLoopbackPort(t),
"--drain-addr", freeLoopbackPort(t),
"--session-lease-k8s-namespace", "",
"--oidc-issuer", h.AS1.Issuer(),
"--oidc-audience", h.AS1.Audience(),
"--oidc-issuer", a.Issuer(),
"--oidc-audience", as1servertest.Audience,
"--oidc-allow-private-https-issuer",
"--oidc-ca-cert-file", h.WriteCACert(t, t.TempDir()),
"--oidc-owner-identity=sub_id",
Expand Down Expand Up @@ -176,15 +181,15 @@ func TestTUISignsInAtAS1AndOpensEachSessionWithAFreshToken(t *testing.T) {
// The client learns its sign-in profile, including whether to send the
// RFC 8707 resource, from mecak8s's protected-resource metadata.
profile := fetchProtectedResourceProfile(t, http.DefaultClient, "http://"+cfg.httpAddr+"/.well-known/oauth-protected-resource")
if len(profile.AuthorizationServers) != 1 || profile.AuthorizationServers[0] != h.AS1.Issuer() || profile.Audience != h.AS1.Audience() || profile.ClientID != identityharness.DefaultClientID {
if len(profile.AuthorizationServers) != 1 || profile.AuthorizationServers[0] != a.Issuer() || profile.Audience != as1servertest.Audience || profile.ClientID != identityharness.DefaultClientID {
t.Fatalf("protected-resource metadata = %+v, want the AS-1 issuer, audience, and client", profile)
}
if !profile.IdentityBrokerSignIn {
t.Fatal("protected-resource metadata does not ask for the resource indicator with --oidc-owner-identity=sub_id")
}
identity := clientauth.Identity{
Target: cfg.grpcAddr, Issuer: profile.AuthorizationServers[0], ClientID: profile.ClientID,
Audience: profile.Audience, RedirectURI: oauthlogin.ExactRedirectURL, Scopes: []string{"openid"},
Audience: profile.Audience, RedirectURI: oauthlogin.ExactRedirectURL, Scopes: []string{"openid", "offline_access"},
}
asClient := h.HTTPClient()
tokenRequests := &resourceRecorder{next: asClient.Transport}
Expand All @@ -193,10 +198,13 @@ func TestTUISignsInAtAS1AndOpensEachSessionWithAFreshToken(t *testing.T) {
if u, err := url.Parse(authorizationURL); err != nil || u.Query().Get("resource") != profile.Audience {
return oauthlogin.Result{}, errors.New("authorization request did not name the audience as resource")
}
back, err := h.Authorize(ctx, authorizationURL)
back, err := h.AuthorizeWithConsent(ctx, authorizationURL)
if err != nil {
return oauthlogin.Result{}, err
}
if back.Get("error") != "" {
return oauthlogin.Result{}, errors.New("authorization refused: " + back.Get("error"))
}
return oauthlogin.Result{Code: back.Get("code"), State: back.Get("state"), Iss: back.Get("iss")}, nil
})
token, err := clientauth.Login(t.Context(), clientauth.LoginConfig{Identity: identity, Presenter: presenter, HTTPClient: asClient, IdentityBrokerSignIn: profile.IdentityBrokerSignIn})
Expand Down
Loading
Loading