package runtimeapi

import (
	"bytes"
	"context"
	"crypto/ed25519"
	"errors"
	navigationsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/applicationnavigationv1"
	"sort"
	"strconv"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	appErrors "github.com/nexuscrm/kernel/pkg/errors"
	"github.com/nexuscrm/shared/pkg/models"
	"github.com/pingcap-inc/nexuscrm-api-host/runtimegrpc"
	catalogsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/catalog/consumerv1"
	approvalnotificationsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/approvalnotificationflowv1"
	approvalsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/approvalv1"
	commandsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/commandv1"
	"github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/delegationv1"
	permissionsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/effectivepermissionsv1"
	filessemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/filesv1"
	flowsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/flowv1"
	mailboxauthorizationsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/mailboxauthorizationv1"
	metadataadminsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/metadataadminreadv1"
	outboundintentsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/outboundintentv1"
	permissionauthoringsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/permissionauthoringv1"
	"github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/permissionstatev1"
	querysemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/queryv1"
	accesssemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/recordaccessv1"
	attachmentsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/recordattachmentsv1"
	defaultsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/recorddefaultsv1"
	mutationsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/recordmutationv1"
	semantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/recordsv1"
	recordviewsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/recordviewv1"
	recyclemutationsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/recyclebinmutationv1"
	recyclesemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/recyclebinv1"
	relatedsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/relatedcountsv1"
	reportsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/reportv1"
	searchsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/searchv1"
	"github.com/pingcap-inc/nexuscrm-contract/wire-go/envelope"
	catalogv1 "github.com/pingcap-inc/nexuscrm-contract/wire-go/gen/catalog/v1"
	runtimev1 "github.com/pingcap-inc/nexuscrm-contract/wire-go/gen/runtime/v1"
	"github.com/pingcap-inc/nexuscrm-contract/wire-go/mapping"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
)

const (
	testWorkloadID      = "spiffe://example.test/ns/runtime/sa/records-client"
	testOrgID           = "org-test"
	testInstallationID  = "01900000-0000-7000-8000-000000000001"
	testRuntimeAudience = "runtime-test"
	testPrincipalID     = "test-user"
	testSessionID       = "session-test"
	testSigningKeyID    = "test-key"
)

var (
	testPrivateKey      = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x42}, ed25519.SeedSize))
	testDelegationToken = mustSignTestDelegation(testClaims(time.Now()))
)

func testClaims(now time.Time) delegationv1.Claims {
	return testClaimsFor(now, semantic.CapabilityName)
}

func testClaimsFor(now time.Time, capability string) delegationv1.Claims {
	return delegationv1.Claims{
		DelegationID: "delegation-test", OrgID: testOrgID, PrincipalID: testPrincipalID,
		SessionID: testSessionID, CallerWorkloadID: testWorkloadID,
		AppInstallationID: testInstallationID, RuntimeAudience: testRuntimeAudience,
		Capabilities: []string{capability}, AuthEpoch: 1, SecurityEpoch: 1,
		IssuedAt: now.Add(-time.Second).Unix(), ExpiresAt: now.Add(5 * time.Minute).Unix(),
	}
}

func testRuntimeAuthorizingSessionState(
	userID string,
	authEpoch uint64,
) *RuntimeSessionState {
	subject := testRuntimeSubject(userID, "profile-"+userID)
	lineage, err := permissionstatev1.LineageFromBytes(
		[]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
	)
	if err != nil {
		panic(err)
	}
	floor, err := permissionstatev1.NewVersion(lineage, 1)
	if err != nil {
		panic(err)
	}
	return &RuntimeSessionState{
		User: models.UserSession{
			ID: userID, ProfileID: subject.ProfileID(),
		},
		AuthEpoch: authEpoch, Subject: subject, PermissionFloor: floor,
	}
}

func testRuntimeSubject(
	userID string,
	profileID string,
) permissionstatev1.Subject {
	subject, err := permissionstatev1.NewSubject(userID, profileID)
	if err != nil {
		panic(err)
	}
	return subject
}

func mustSignTestDelegation(claims delegationv1.Claims) string {
	token, err := delegationv1.Sign(testSigningKeyID, testPrivateKey, claims)
	if err != nil {
		panic(err)
	}
	return token
}

func testVerifier(t *testing.T) *delegationv1.Verifier {
	t.Helper()
	supportedCapabilities := []string{
		accesssemantic.CapabilityName, recyclesemantic.CapabilityName, recyclemutationsemantic.CapabilityName, mutationsemantic.CapabilityName,
		semantic.CapabilityName, relatedsemantic.CapabilityName, recordviewsemantic.CapabilityName,
		attachmentsemantic.CapabilityName, defaultsemantic.CapabilityName,
		querysemantic.CapabilityName, searchsemantic.CapabilityName,
		reportsemantic.CapabilityName, filessemantic.CapabilityName,
		metadataadminsemantic.CapabilityName, navigationsemantic.CapabilityName,
		approvalnotificationsemantic.CapabilityName,
		approvalsemantic.ExecuteCapabilityName, approvalsemantic.ReadCapabilityName,
		permissionsemantic.CapabilityName, permissionauthoringsemantic.CapabilityName,
		commandsemantic.CapabilityName,
		outboundintentsemantic.CapabilityName,
		catalogsemantic.AppMetadataCapabilityName,
		catalogsemantic.AppMetadataV2CapabilityName,
		catalogsemantic.IntegrationBindingCapabilityName,
		flowsemantic.CapabilityName,
		mailboxauthorizationsemantic.CapabilityName,
	}
	sort.Strings(supportedCapabilities)
	verifier, err := delegationv1.NewVerifier(delegationv1.VerifierConfig{
		Keys: []delegationv1.VerificationKey{{
			SigningKeyID: testSigningKeyID, PublicKey: testPrivateKey.Public().(ed25519.PublicKey),
			State: delegationv1.KeyStateCurrent,
		}},
		SupportedCapabilities: supportedCapabilities,
	})
	if err != nil {
		t.Fatal(err)
	}
	return verifier
}

func testRuntimeSecurityState(t *testing.T) *RuntimeSecurityState {
	t.Helper()
	now := time.Now
	state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Now: now,
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			return RuntimeReplicaSecurityState{
				OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 1,
				LeaseSecurityEpoch: 1, LeaseExpiresAt: now().Add(time.Hour),
			}, true, nil
		},
		Admission: func(_ context.Context, claims delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			return RuntimeAdmissionSecurityState{
				StateFound: true, InstallationFound: claims.AppInstallationID == testInstallationID,
				InstallationActive: true, Capabilities: []string{
					semantic.CapabilityName, accesssemantic.CapabilityName, mutationsemantic.CapabilityName,
					recyclesemantic.CapabilityName, recyclemutationsemantic.CapabilityName, relatedsemantic.CapabilityName, recordviewsemantic.CapabilityName,
					attachmentsemantic.CapabilityName, defaultsemantic.CapabilityName,
					querysemantic.CapabilityName, searchsemantic.CapabilityName,
					reportsemantic.CapabilityName, filessemantic.CapabilityName,
					metadataadminsemantic.CapabilityName, navigationsemantic.CapabilityName,
					approvalnotificationsemantic.CapabilityName,
					permissionsemantic.CapabilityName, permissionauthoringsemantic.CapabilityName,
					commandsemantic.CapabilityName,
					outboundintentsemantic.CapabilityName,
					mailboxauthorizationsemantic.CapabilityName,
				},
				SecurityEpoch: 1, LeaseFound: true, LeaseSecurityEpoch: 1, LeaseExpiresAt: now().Add(time.Hour),
			}, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	return state
}

func testSecurityAdmission(t *testing.T) *SecurityAdmission {
	t.Helper()
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t),
		Bindings: func(_ context.Context, caller runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, caller == testWorkloadID, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			return testRuntimeAuthorizingSessionState(testPrincipalID, 1), nil
		},
		State: testRuntimeSecurityState(t),
	})
	if err != nil {
		t.Fatal(err)
	}
	return admission
}

func testWorkloadAuthority(context.Context, string) (runtimegrpc.VerifiedCaller, error) {
	return runtimegrpc.VerifiedCaller(testWorkloadID), nil
}

func TestSecurityAdmissionRevalidatesAuthorityForEveryAttempt(t *testing.T) {
	now := time.Date(2026, 7, 13, 12, 0, 0, 0, time.UTC)
	var stateCalls atomic.Int64
	state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Now: func() time.Time { return now },
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			return RuntimeReplicaSecurityState{
				OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 1,
				LeaseSecurityEpoch: 1, LeaseExpiresAt: now.Add(time.Minute),
			}, true, nil
		},
		Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			stateCalls.Add(1)
			return RuntimeAdmissionSecurityState{
				StateFound: true, InstallationFound: true, InstallationActive: true,
				Capabilities: []string{semantic.CapabilityName}, SecurityEpoch: 1,
				LeaseFound: true, LeaseSecurityEpoch: 1, LeaseExpiresAt: now.Add(time.Minute),
			}, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	var sessionCalls atomic.Int64
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t), State: state,
		Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			sessionCalls.Add(1)
			return testRuntimeAuthorizingSessionState(testPrincipalID, 1), nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	token := mustSignTestDelegation(testClaims(now))
	var handlerCalls atomic.Int64
	for attempt := 0; attempt < 2; attempt++ {
		if err := invokeSecurityChain(t, admission, testWorkloadID, token, 1, func(context.Context) {
			handlerCalls.Add(1)
		}); err != nil {
			t.Fatalf("attempt %d: %v", attempt+1, err)
		}
	}
	if stateCalls.Load() != 2 || sessionCalls.Load() != 2 || handlerCalls.Load() != 2 {
		t.Fatalf("two attempts called state/session/handler = %d/%d/%d, want 2/2/2", stateCalls.Load(), sessionCalls.Load(), handlerCalls.Load())
	}
}

func withTestDelegation(ctx context.Context, token string) context.Context {
	return metadata.AppendToOutgoingContext(ctx, envelope.RuntimeDelegationMetadataKey, token)
}

func TestSecurityAdmissionStableFailureMatrixStopsBeforeHandler(t *testing.T) {
	now := time.Now()
	valid := testClaims(now)
	tampered := mustSignTestDelegation(valid)
	if tampered[len(tampered)-1] == 'A' {
		tampered = tampered[:len(tampered)-1] + "B"
	} else {
		tampered = tampered[:len(tampered)-1] + "A"
	}
	expired := valid
	expired.IssuedAt = now.Add(-2 * time.Minute).Unix()
	expired.ExpiresAt = now.Add(-time.Minute).Unix()
	wrongAudience := valid
	wrongAudience.RuntimeAudience = "runtime-other"
	wrongOrg := valid
	wrongOrg.OrgID = "org-other"
	wrongApp := valid
	wrongApp.AppInstallationID = "installation-other"
	wrongCapability := valid
	wrongCapability.Capabilities = []string{"runtime.records.other.v1"}

	tests := []struct {
		name          string
		token         string
		metadataCount int
		workload      runtimegrpc.VerifiedCaller
		claims        *delegationv1.Claims
		bindingFound  bool
		sessionErr    error
		sessionUserID string
		want          semantic.FailureCategory
		wantSessions  int64
	}{
		{name: "missing", workload: testWorkloadID, bindingFound: true, want: semantic.FailureUnauthenticated},
		{name: "malformed", token: "not-a-jws", metadataCount: 1, workload: testWorkloadID, bindingFound: true, want: semantic.FailureUnauthenticated},
		{name: "duplicate", token: mustSignTestDelegation(valid), metadataCount: 2, workload: testWorkloadID, bindingFound: true, want: semantic.FailureUnauthenticated},
		{name: "tampered", token: tampered, metadataCount: 1, workload: testWorkloadID, bindingFound: true, want: semantic.FailureUnauthenticated},
		{name: "expired", claims: &expired, metadataCount: 1, workload: testWorkloadID, bindingFound: true, want: semantic.FailureUnauthenticated},
		{name: "wrong-audience", claims: &wrongAudience, metadataCount: 1, workload: testWorkloadID, bindingFound: true, want: semantic.FailureUnauthenticated},
		{name: "workload-mismatch", claims: &valid, metadataCount: 1, workload: "spiffe://example.test/ns/runtime/sa/other", bindingFound: true, want: semantic.FailureForbidden},
		{name: "wrong-org", claims: &wrongOrg, metadataCount: 1, workload: testWorkloadID, bindingFound: true, want: semantic.FailureForbidden},
		{name: "wrong-app-installation", claims: &wrongApp, metadataCount: 1, workload: testWorkloadID, bindingFound: true, want: semantic.FailureForbidden},
		{name: "missing-capability", claims: &wrongCapability, metadataCount: 1, workload: testWorkloadID, bindingFound: true, want: semantic.FailureForbidden},
		{name: "unauthorized-workload", claims: &valid, metadataCount: 1, workload: testWorkloadID, bindingFound: false, want: semantic.FailureForbidden},
		{name: "revoked-session", claims: &valid, metadataCount: 1, workload: testWorkloadID, bindingFound: true, sessionErr: appErrors.NewUnauthorizedError("revoked"), want: semantic.FailureUnauthenticated, wantSessions: 1},
		{name: "session-principal-mismatch", claims: &valid, metadataCount: 1, workload: testWorkloadID, bindingFound: true, sessionUserID: "other-user", want: semantic.FailureUnauthenticated, wantSessions: 1},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			token := test.token
			if test.claims != nil {
				token = mustSignTestDelegation(*test.claims)
			}
			var sessionCalls atomic.Int64
			admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
				Verifier: testVerifier(t),
				Bindings: func(_ context.Context, caller runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
					return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, test.bindingFound && caller == testWorkloadID, nil
				},
				Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
					sessionCalls.Add(1)
					if test.sessionErr != nil {
						return nil, test.sessionErr
					}
					userID := test.sessionUserID
					if userID == "" {
						userID = testPrincipalID
					}
					return testRuntimeAuthorizingSessionState(userID, 1), nil
				},
				State: testRuntimeSecurityState(t),
			})
			if err != nil {
				t.Fatal(err)
			}
			var handlerCalls atomic.Int64
			callErr := invokeSecurityChain(t, admission, test.workload, token, test.metadataCount, func(context.Context) {
				handlerCalls.Add(1)
			})
			if got := failureCategoryForTest(callErr); got != test.want {
				t.Fatalf("failure = %s (%v), want %s", got, callErr, test.want)
			}
			if handlerCalls.Load() != 0 || sessionCalls.Load() != test.wantSessions {
				t.Fatalf("handler calls=%d session calls=%d, want 0/%d", handlerCalls.Load(), sessionCalls.Load(), test.wantSessions)
			}
		})
	}
}

func TestRuntimeSecurityStateAuthoritativeFailureMatrix(t *testing.T) {
	now := time.Date(2026, 7, 12, 12, 0, 0, 0, time.UTC)
	claims := testClaims(now)
	base := RuntimeAdmissionSecurityState{
		StateFound: true, InstallationFound: true, InstallationActive: true,
		Capabilities: []string{semantic.CapabilityName}, SecurityEpoch: 1,
		LeaseFound: true, LeaseSecurityEpoch: 1, LeaseExpiresAt: now.Add(time.Minute),
	}
	tests := []struct {
		name   string
		mutate func(*RuntimeAdmissionSecurityState)
		err    error
		want   semantic.FailureCategory
		ready  bool
	}{
		{name: "revoked delegation", mutate: func(s *RuntimeAdmissionSecurityState) { s.DelegationRevoked = true }, want: semantic.FailureUnauthenticated, ready: true},
		{name: "missing state", mutate: func(s *RuntimeAdmissionSecurityState) { s.StateFound = false }, want: semantic.FailureForbidden, ready: true},
		{name: "missing installation", mutate: func(s *RuntimeAdmissionSecurityState) { s.InstallationFound = false }, want: semantic.FailureForbidden, ready: true},
		{name: "inactive installation", mutate: func(s *RuntimeAdmissionSecurityState) { s.InstallationActive = false }, want: semantic.FailureForbidden, ready: true},
		{name: "removed capability", mutate: func(s *RuntimeAdmissionSecurityState) { s.Capabilities = nil }, want: semantic.FailureForbidden, ready: true},
		{name: "old security epoch", mutate: func(s *RuntimeAdmissionSecurityState) { s.SecurityEpoch = 2; s.LeaseSecurityEpoch = 2 }, want: semantic.FailureStaleState},
		{name: "missing lease", mutate: func(s *RuntimeAdmissionSecurityState) { s.LeaseFound = false }, want: semantic.FailureStaleState},
		{name: "lease epoch mismatch", mutate: func(s *RuntimeAdmissionSecurityState) { s.LeaseSecurityEpoch = 2 }, want: semantic.FailureStaleState},
		{name: "malformed zero lease expiry", mutate: func(s *RuntimeAdmissionSecurityState) { s.LeaseExpiresAt = time.Time{} }, want: semantic.FailureStaleState},
		{name: "superseded expired lease", mutate: func(s *RuntimeAdmissionSecurityState) { s.LeaseExpiresAt = now }, want: semantic.FailureStaleState, ready: true},
		{name: "authority partition", err: errors.New("partition"), want: semantic.FailureUnavailable, ready: true},
		{name: "authority internal deadline", err: context.DeadlineExceeded, want: semantic.FailureUnavailable, ready: true},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			state := base
			var admissionCalls atomic.Int64
			if test.mutate != nil {
				test.mutate(&state)
			}
			securityState, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
				Now: func() time.Time { return now },
				Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
					return RuntimeReplicaSecurityState{OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 1, LeaseSecurityEpoch: 1, LeaseExpiresAt: now.Add(time.Minute)}, true, nil
				},
				Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
					admissionCalls.Add(1)
					return state, test.err
				},
			})
			if err != nil {
				t.Fatal(err)
			}
			admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
				Verifier: testVerifier(t), State: securityState,
				Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
					return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
				},
				Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
					t.Fatal("security denial reached session authority")
					return nil, nil
				},
			})
			if err != nil {
				t.Fatal(err)
			}
			var handlerCalls atomic.Int64
			callErr := invokeSecurityChain(t, admission, testWorkloadID, mustSignTestDelegation(claims), 1, func(context.Context) { handlerCalls.Add(1) })
			if got := failureCategoryForTest(callErr); got != test.want || handlerCalls.Load() != 0 {
				t.Fatalf("failure=%s err=%v handler=%d, want %s/0", got, callErr, handlerCalls.Load(), test.want)
			}
			if got := admission.Ready(); got != test.ready {
				t.Fatalf("Ready after denial = %v, want %v", got, test.ready)
			}
			if test.err != nil {
				followupErr := invokeSecurityChain(t, admission, testWorkloadID, mustSignTestDelegation(claims), 1, func(context.Context) {
					t.Fatal("authority-outage follow-up reached handler")
				})
				if got := failureCategoryForTest(followupErr); got != semantic.FailureUnavailable || admissionCalls.Load() != 2 {
					t.Fatalf("authority-outage follow-up=%s err=%v admission calls=%d, want unavailable/2", got, followupErr, admissionCalls.Load())
				}
			}
		})
	}
}

func TestAdmissionOwnerFailureDoesNotPoisonIndependentFollowup(t *testing.T) {
	now := time.Date(2026, 8, 17, 6, 24, 39, 0, time.UTC)
	claims := testClaims(now)
	var admissionCalls atomic.Int64
	state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Now: func() time.Time { return now },
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			return RuntimeReplicaSecurityState{
				OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 1,
				LeaseSecurityEpoch: 1, LeaseExpiresAt: now.Add(22 * time.Second),
			}, true, nil
		},
		Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			if admissionCalls.Add(1) == 1 {
				return RuntimeAdmissionSecurityState{}, context.DeadlineExceeded
			}
			return RuntimeAdmissionSecurityState{
				StateFound: true, InstallationFound: true, InstallationActive: true,
				Capabilities: []string{semantic.CapabilityName}, SecurityEpoch: 1,
				LeaseFound: true, LeaseSecurityEpoch: 1, LeaseExpiresAt: now.Add(22 * time.Second),
			}, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t), State: state,
		Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			return testRuntimeAuthorizingSessionState(testPrincipalID, 1), nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	first := invokeSecurityChain(t, admission, testWorkloadID, mustSignTestDelegation(claims), 1, func(context.Context) {
		t.Fatal("failed authority read reached handler")
	})
	if got := failureCategoryForTest(first); got != semantic.FailureUnavailable || !admission.Ready() {
		t.Fatalf("first failure=%s err=%v ready=%v", got, first, admission.Ready())
	}
	var handled atomic.Int64
	second := invokeSecurityChain(t, admission, testWorkloadID, mustSignTestDelegation(claims), 1, func(context.Context) {
		handled.Add(1)
	})
	if second != nil || handled.Load() != 1 || admissionCalls.Load() != 2 {
		t.Fatalf("followup err=%v handled=%d admission_calls=%d", second, handled.Load(), admissionCalls.Load())
	}
}

func TestDelayedAdmissionSnapshotCannotRollBackRenewedReplicaLease(t *testing.T) {
	now := time.Date(2026, 8, 26, 0, 45, 0, 0, time.UTC)
	clock := now
	claims := testClaims(now)
	state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Now: func() time.Time { return clock },
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			return RuntimeReplicaSecurityState{
				OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 2,
				LeaseSecurityEpoch: 2, LeaseExpiresAt: now.Add(30 * time.Second),
			}, true, nil
		},
		Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			return RuntimeAdmissionSecurityState{
				StateFound: true, InstallationFound: true, InstallationActive: true,
				Capabilities: []string{semantic.CapabilityName}, SecurityEpoch: 2,
				LeaseFound: true, LeaseSecurityEpoch: 2, LeaseExpiresAt: now.Add(5 * time.Second),
			}, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t), State: state,
		Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			return testRuntimeAuthorizingSessionState(testPrincipalID, 1), nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	claims.SecurityEpoch = 2
	var handlers atomic.Int64
	if err := invokeSecurityChain(t, admission, testWorkloadID, mustSignTestDelegation(claims), 1, func(context.Context) {
		handlers.Add(1)
	}); err != nil || handlers.Load() != 1 {
		t.Fatalf("delayed valid snapshot err=%v handlers=%d", err, handlers.Load())
	}
	clock = now.Add(6 * time.Second)
	if !admission.Ready() {
		t.Fatal("delayed admission snapshot rolled the renewed replica lease backward")
	}
}

func TestExpiredSupersededAdmissionSnapshotDoesNotPoisonRenewedReplica(t *testing.T) {
	now := time.Date(2026, 8, 26, 0, 45, 0, 0, time.UTC)
	claims := testClaims(now)
	claims.SecurityEpoch = 2
	var admissionCalls atomic.Int64
	state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Now: func() time.Time { return now },
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			return RuntimeReplicaSecurityState{
				OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 2,
				LeaseSecurityEpoch: 2, LeaseExpiresAt: now.Add(30 * time.Second),
			}, true, nil
		},
		Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			expiresAt := now.Add(30 * time.Second)
			if admissionCalls.Add(1) == 1 {
				expiresAt = now
			}
			return RuntimeAdmissionSecurityState{
				StateFound: true, InstallationFound: true, InstallationActive: true,
				Capabilities: []string{semantic.CapabilityName}, SecurityEpoch: 2,
				LeaseFound: true, LeaseSecurityEpoch: 2, LeaseExpiresAt: expiresAt,
			}, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t), State: state,
		Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			return testRuntimeAuthorizingSessionState(testPrincipalID, 1), nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	first := invokeSecurityChain(t, admission, testWorkloadID, mustSignTestDelegation(claims), 1, func(context.Context) {
		t.Fatal("expired snapshot reached handler")
	})
	if got := failureCategoryForTest(first); got != semantic.FailureStaleState || !admission.Ready() {
		t.Fatalf("superseded snapshot failure=%s err=%v ready=%v", got, first, admission.Ready())
	}
	var handlers atomic.Int64
	second := invokeSecurityChain(t, admission, testWorkloadID, mustSignTestDelegation(claims), 1, func(context.Context) {
		handlers.Add(1)
	})
	if second != nil || handlers.Load() != 1 || admissionCalls.Load() != 2 {
		t.Fatalf("fresh followup err=%v handlers=%d admission_calls=%d", second, handlers.Load(), admissionCalls.Load())
	}
}

func TestCurrentExpiredAdmissionSnapshotPoisonsReplicaReadiness(t *testing.T) {
	start := time.Date(2026, 8, 26, 0, 45, 0, 0, time.UTC)
	clock := start
	expiresAt := start.Add(time.Second)
	claims := testClaims(start)
	state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Now: func() time.Time { return clock },
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			return RuntimeReplicaSecurityState{
				OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 1,
				LeaseSecurityEpoch: 1, LeaseExpiresAt: expiresAt,
			}, true, nil
		},
		Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			clock = expiresAt
			return RuntimeAdmissionSecurityState{
				StateFound: true, InstallationFound: true, InstallationActive: true,
				Capabilities: []string{semantic.CapabilityName}, SecurityEpoch: 1,
				LeaseFound: true, LeaseSecurityEpoch: 1, LeaseExpiresAt: expiresAt,
			}, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t), State: state,
		Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			t.Fatal("expired current lease reached session authority")
			return nil, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	callErr := invokeSecurityChain(t, admission, testWorkloadID, mustSignTestDelegation(claims), 1, func(context.Context) {
		t.Fatal("expired current lease reached handler")
	})
	if got := failureCategoryForTest(callErr); got != semantic.FailureStaleState || admission.Ready() {
		t.Fatalf("current expired snapshot failure=%s err=%v ready=%v", got, callErr, admission.Ready())
	}
}

func TestStaleCallerSecurityEpochDoesNotPoisonRuntimeReadiness(t *testing.T) {
	now := time.Date(2026, 8, 10, 0, 0, 0, 0, time.UTC)
	currentEpoch := uint64(2)
	securityState, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Now: func() time.Time { return now },
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			return RuntimeReplicaSecurityState{
				OrgID: testOrgID, RuntimeAudience: testRuntimeAudience,
				SecurityEpoch: currentEpoch, LeaseSecurityEpoch: currentEpoch,
				LeaseExpiresAt: now.Add(time.Minute),
			}, true, nil
		},
		Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			return RuntimeAdmissionSecurityState{
				StateFound: true, InstallationFound: true, InstallationActive: true,
				Capabilities: []string{semantic.CapabilityName}, SecurityEpoch: currentEpoch,
				LeaseFound: true, LeaseSecurityEpoch: currentEpoch, LeaseExpiresAt: now.Add(time.Minute),
			}, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t), State: securityState,
		Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			return testRuntimeAuthorizingSessionState(testPrincipalID, 1), nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}

	staleClaims := testClaims(now)
	staleClaims.SecurityEpoch = currentEpoch - 1
	staleErr := invokeSecurityChain(t, admission, testWorkloadID, mustSignTestDelegation(staleClaims), 1, func(context.Context) {
		t.Fatal("stale caller reached handler")
	})
	if got := failureCategoryForTest(staleErr); got != semantic.FailureStaleState || !admission.Ready() {
		t.Fatalf("stale caller failure=%s err=%v ready=%v", got, staleErr, admission.Ready())
	}

	currentClaims := testClaims(now)
	currentClaims.SecurityEpoch = currentEpoch
	var handlerCalls atomic.Int64
	if err := invokeSecurityChain(t, admission, testWorkloadID, mustSignTestDelegation(currentClaims), 1, func(context.Context) {
		handlerCalls.Add(1)
	}); err != nil || handlerCalls.Load() != 1 {
		t.Fatalf("current caller after stale caller err=%v handler=%d", err, handlerCalls.Load())
	}
}

func TestSecurityAdmissionRejectsOldAuthEpoch(t *testing.T) {
	admission := testSecurityAdmission(t)
	admission.sessions = func(context.Context, string, string) (*RuntimeSessionState, error) {
		return testRuntimeAuthorizingSessionState(testPrincipalID, 2), nil
	}
	var handlerCalls atomic.Int64
	err := invokeSecurityChain(t, admission, testWorkloadID, testDelegationToken, 1, func(context.Context) { handlerCalls.Add(1) })
	if failureCategoryForTest(err) != semantic.FailureUnauthenticated || handlerCalls.Load() != 0 {
		t.Fatalf("old AuthEpoch = %v handler=%d", err, handlerCalls.Load())
	}
}

func TestSecurityAdmissionRejectsInconsistentCurrentPermissionAuthority(t *testing.T) {
	for _, test := range []struct {
		name   string
		mutate func(*RuntimeSessionState)
	}{
		{
			name: "missing floor",
			mutate: func(state *RuntimeSessionState) {
				state.PermissionFloor = permissionstatev1.Version{}
			},
		},
		{
			name: "subject profile differs from current user projection",
			mutate: func(state *RuntimeSessionState) {
				subject, err := permissionstatev1.NewSubject(
					testPrincipalID,
					"profile-other",
				)
				if err != nil {
					t.Fatal(err)
				}
				state.Subject = subject
			},
		},
	} {
		t.Run(test.name, func(t *testing.T) {
			admission := testSecurityAdmission(t)
			admission.sessions = func(
				context.Context,
				string,
				string,
			) (*RuntimeSessionState, error) {
				state := testRuntimeAuthorizingSessionState(testPrincipalID, 1)
				test.mutate(state)
				return state, nil
			}
			var handlerCalls atomic.Int64
			err := invokeSecurityChain(
				t,
				admission,
				testWorkloadID,
				testDelegationToken,
				1,
				func(context.Context) { handlerCalls.Add(1) },
			)
			if failureCategoryForTest(err) != semantic.FailureUnavailable ||
				handlerCalls.Load() != 0 {
				t.Fatalf(
					"inconsistent authority = %v handler=%d",
					err,
					handlerCalls.Load(),
				)
			}
		})
	}
}

func TestRuntimeSecurityStateLeaseExpiryControlsReadiness(t *testing.T) {
	now := time.Date(2026, 7, 12, 12, 0, 0, 0, time.UTC)
	clock := now
	leaseExpiry := now.Add(time.Second)
	state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Now: func() time.Time { return clock },
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			return RuntimeReplicaSecurityState{OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 1, LeaseSecurityEpoch: 1, LeaseExpiresAt: leaseExpiry}, true, nil
		},
		Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			return RuntimeAdmissionSecurityState{}, nil
		},
	})
	if err != nil || !state.Ready() {
		t.Fatalf("initial state = %#v, %v", state, err)
	}
	clock = now.Add(time.Second)
	if state.Ready() {
		t.Fatal("security state remained ready at exclusive lease expiry")
	}
	leaseExpiry = clock.Add(time.Minute)
	if err := state.Refresh(context.Background()); err != nil || !state.Ready() {
		t.Fatalf("renewed authoritative lease did not restore readiness: ready=%v err=%v", state.Ready(), err)
	}
}

func TestRuntimeSecurityStateRefreshPreservesAuthoritativeIdentityAndFailureReason(t *testing.T) {
	now := time.Date(2026, 7, 12, 12, 0, 0, 0, time.UTC)
	validReplica := RuntimeReplicaSecurityState{
		OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 1,
		LeaseSecurityEpoch: 1, LeaseExpiresAt: now.Add(time.Minute),
	}
	for _, test := range []struct {
		name    string
		refresh RuntimeReplicaSecurityState
		found   bool
		want    semantic.FailureCategory
	}{
		{name: "missing authority state", found: false, want: semantic.FailureUnavailable},
		{name: "invalid different authority identity", refresh: RuntimeReplicaSecurityState{
			OrgID: "org-other", RuntimeAudience: "runtime-other", SecurityEpoch: 2,
		}, found: true, want: semantic.FailureStaleState},
	} {
		t.Run(test.name, func(t *testing.T) {
			replica, found := validReplica, true
			state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
				Now: func() time.Time { return now },
				Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
					return replica, found, nil
				},
				Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
					t.Fatal("invalid refresh reached admission state owner")
					return RuntimeAdmissionSecurityState{}, nil
				},
			})
			if err != nil || !state.Ready() {
				t.Fatalf("initial state ready=%v err=%v", state.Ready(), err)
			}
			replica, found = test.refresh, test.found
			if err := state.Refresh(context.Background()); err != nil || state.Ready() {
				t.Fatalf("refresh ready=%v err=%v", state.Ready(), err)
			}
			identity, known := state.verificationReplica()
			if !known || identity.OrgID != testOrgID || identity.RuntimeAudience != testRuntimeAudience {
				t.Fatalf("last authoritative identity = %#v known=%v", identity, known)
			}
			admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
				Verifier: testVerifier(t), State: state,
				Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
					return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
				},
				Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
					t.Fatal("invalid refresh reached session owner")
					return nil, nil
				},
			})
			if err != nil {
				t.Fatal(err)
			}
			malformed := invokeSecurityChain(t, admission, testWorkloadID, "not-a-jws", 1, func(context.Context) {
				t.Fatal("malformed delegation reached handler")
			})
			if got := failureCategoryForTest(malformed); got != semantic.FailureUnauthenticated {
				t.Fatalf("malformed failure=%s err=%v, want unauthenticated", got, malformed)
			}
			valid := invokeSecurityChain(t, admission, testWorkloadID, mustSignTestDelegation(testClaims(now)), 1, func(context.Context) {
				t.Fatal("invalid refresh reached handler")
			})
			if got := failureCategoryForTest(valid); got != test.want {
				t.Fatalf("valid delegation failure=%s err=%v, want %s", got, valid, test.want)
			}
		})
	}
}

func TestExpiredLeaseAuthenticatesDelegationBeforeStaleState(t *testing.T) {
	now := time.Date(2026, 7, 12, 12, 0, 0, 0, time.UTC)
	clock := now
	state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Now: func() time.Time { return clock },
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			return RuntimeReplicaSecurityState{
				OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 1,
				LeaseSecurityEpoch: 1, LeaseExpiresAt: now.Add(time.Second),
			}, true, nil
		},
		Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			t.Fatal("expired lease reached admission state owner")
			return RuntimeAdmissionSecurityState{}, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	clock = now.Add(time.Second)
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t), State: state,
		Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			t.Fatal("expired lease reached session owner")
			return nil, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	for _, test := range []struct {
		name  string
		token string
		count int
		want  semantic.FailureCategory
	}{
		{name: "missing", want: semantic.FailureUnauthenticated},
		{name: "malformed", token: "not-a-jws", count: 1, want: semantic.FailureUnauthenticated},
		{name: "valid", token: mustSignTestDelegation(testClaims(now)), count: 1, want: semantic.FailureStaleState},
	} {
		t.Run(test.name, func(t *testing.T) {
			err := invokeSecurityChain(t, admission, testWorkloadID, test.token, test.count, func(context.Context) {
				t.Fatal("expired lease reached handler")
			})
			if got := failureCategoryForTest(err); got != test.want {
				t.Fatalf("failure = %s (%v), want %s", got, err, test.want)
			}
		})
	}
}

func TestSecurityAdmissionWithoutReplicaIdentityFailsUnavailable(t *testing.T) {
	state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			return RuntimeReplicaSecurityState{}, false, nil
		},
		Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			t.Fatal("missing replica identity reached admission state owner")
			return RuntimeAdmissionSecurityState{}, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t), State: state,
		Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			t.Fatal("missing replica identity reached session owner")
			return nil, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	for _, test := range []struct {
		name  string
		token string
		count int
		want  semantic.FailureCategory
	}{
		{name: "missing delegation", want: semantic.FailureUnauthenticated},
		{name: "malformed delegation masked by missing audience authority", token: "not-a-jws", count: 1, want: semantic.FailureUnavailable},
		{name: "valid delegation cannot be audience-bound", token: testDelegationToken, count: 1, want: semantic.FailureUnavailable},
	} {
		t.Run(test.name, func(t *testing.T) {
			err := invokeSecurityChain(t, admission, testWorkloadID, test.token, test.count, func(context.Context) {
				t.Fatal("missing replica identity reached handler")
			})
			if got := failureCategoryForTest(err); got != test.want {
				t.Fatalf("failure = %s (%v), want %s", got, err, test.want)
			}
		})
	}
}

func TestSecurityAdmissionValidDelegationInstallsIndependentTrustedCall(t *testing.T) {
	email := "user@example.test"
	roleID := "role-1"
	sharedUser := &models.UserSession{ID: testPrincipalID, ProfileID: "profile-1", Email: &email, RoleID: &roleID}
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t),
		Bindings: func(_ context.Context, caller runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, caller == testWorkloadID, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			state := testRuntimeAuthorizingSessionState(testPrincipalID, 1)
			state.User = *sharedUser
			state.Subject = testRuntimeSubject(testPrincipalID, "profile-1")
			return state, nil
		},
		State: testRuntimeSecurityState(t),
	})
	if err != nil {
		t.Fatal(err)
	}

	var wg sync.WaitGroup
	for range 64 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			err := invokeSecurityChain(t, admission, testWorkloadID, testDelegationToken, 1, func(ctx context.Context) {
				trusted, ok := trustedCallFromContext(ctx)
				if !ok {
					t.Error("TrustedCall missing")
					return
				}
				user := trusted.UserSession()
				capabilities := trusted.Capabilities()
				subject := trusted.Subject()
				floor := trusted.PermissionFloor()
				if subject.UserID() != testPrincipalID ||
					subject.ProfileID() != "profile-1" ||
					floor.Revision() != 1 {
					t.Errorf("TrustedCall authority = %#v / %#v", subject, floor)
				}
				*user.Email = "mutated@example.test"
				*user.RoleID = "mutated-role"
				capabilities[0] = "mutated.capability"
				second := trusted.UserSession()
				secondCapabilities := trusted.Capabilities()
				if *second.Email != email || *second.RoleID != roleID || secondCapabilities[0] != semantic.CapabilityName {
					t.Errorf("TrustedCall mutation escaped defensive copies: user=%#v capabilities=%v", second, secondCapabilities)
				}
			})
			if err != nil {
				t.Errorf("valid chain: %v", err)
			}
		}()
	}
	wg.Wait()
	if *sharedUser.Email != email || *sharedUser.RoleID != roleID {
		t.Fatalf("admission mutated session authority result: %#v", sharedUser)
	}
}

func TestSecurityAdmissionWorkloadConsumerDoesNotCreateUserSession(t *testing.T) {
	var sessionCalls atomic.Int64
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t),
		Bindings: func(_ context.Context, caller runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, caller == testWorkloadID, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			sessionCalls.Add(1)
			return nil, errors.New("workload consumer must not read a user session")
		},
		State: testRuntimeSecurityState(t),
	})
	if err != nil {
		t.Fatal(err)
	}
	ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(
		envelope.ProtocolMajorMetadataKey, strconv.FormatUint(uint64(catalogsemantic.ProtocolMajor), 10),
		envelope.ProtocolMinorMetadataKey, strconv.FormatUint(uint64(catalogsemantic.ProtocolMinor), 10),
		envelope.CapabilityMetadataKey, catalogsemantic.AppMetadataCapabilityName,
	))
	ctx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	policy, err := runtimegrpc.NewPolicyWithOptions(runtimegrpc.Config{
		Authority: func(context.Context, string) (runtimegrpc.VerifiedCaller, error) {
			return runtimegrpc.VerifiedCaller(testWorkloadID), nil
		},
		AdmissionLimit: 1, AttemptCap: time.Second,
	}, runtimegrpc.WithPlatformCapabilityMaxAdmissionLease(
		catalogsemantic.AppMetadataCapabilityName, time.Second,
	), runtimegrpc.WithResourceClassAdmissionLimit(
		runtimegrpc.ResourceClassCatalogWatch, 1,
	))
	if err != nil {
		t.Fatal(err)
	}
	info := &grpc.UnaryServerInfo{
		FullMethod: catalogv1.ConsumerViewService_GetAppMetadataView_FullMethodName,
	}
	_, err = policy.UnaryServerInterceptor()(ctx, nil, info, func(ctx context.Context, request any) (any, error) {
		return admission.UnaryServerInterceptor()(ctx, request, info, func(ctx context.Context, _ any) (any, error) {
			workload, ok := trustedWorkloadCallFromContext(ctx)
			if !ok || workload.orgID != testOrgID ||
				workload.callerWorkloadID != testWorkloadID ||
				workload.capability != catalogsemantic.AppMetadataCapabilityName ||
				workload.securityEpoch != 1 {
				t.Fatalf("trusted workload call = %#v, %v", workload, ok)
			}
			if _, ok := trustedCallFromContext(ctx); ok {
				t.Fatal("workload consumer received a delegated user context")
			}
			return struct{}{}, nil
		})
	})
	if err != nil {
		t.Fatal(err)
	}
	if sessionCalls.Load() != 0 {
		t.Fatalf("user session reads = %d, want 0", sessionCalls.Load())
	}
}

func TestSecurityAdmissionWorkloadConsumerRequiresConfirmedReplicaRefresh(t *testing.T) {
	now := time.Date(2026, 8, 19, 12, 0, 0, 0, time.UTC)
	refreshErr := false
	state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Now: func() time.Time { return now },
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			if refreshErr {
				return RuntimeReplicaSecurityState{}, false, errors.New("replica authority unavailable")
			}
			return RuntimeReplicaSecurityState{
				OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 1,
				LeaseSecurityEpoch: 1, LeaseExpiresAt: now.Add(time.Minute),
			}, true, nil
		},
		Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			return RuntimeAdmissionSecurityState{}, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t), State: state,
		Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			t.Fatal("workload consumer reached user session owner")
			return nil, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}

	var handlerCalls atomic.Int64
	call := func() error {
		return invokeWorkloadSecurityChain(t, admission, func(context.Context) {
			handlerCalls.Add(1)
		})
	}
	if err := call(); err != nil || handlerCalls.Load() != 1 {
		t.Fatalf("initial workload call err=%v handlers=%d", err, handlerCalls.Load())
	}

	refreshErr = true
	if err := state.Refresh(context.Background()); err == nil || !state.Ready() {
		t.Fatalf("transient refresh err=%v ready=%v, want error with delegated readiness preserved", err, state.Ready())
	}
	if err := call(); failureCategoryForTest(err) != semantic.FailureUnavailable || handlerCalls.Load() != 1 {
		t.Fatalf("uncertain workload authority err=%v handlers=%d", err, handlerCalls.Load())
	}

	refreshErr = false
	if err := state.Refresh(context.Background()); err != nil || !state.Ready() {
		t.Fatalf("restored refresh err=%v ready=%v", err, state.Ready())
	}
	if err := call(); err != nil || handlerCalls.Load() != 2 {
		t.Fatalf("restored workload call err=%v handlers=%d", err, handlerCalls.Load())
	}
}

func TestSecurityAdmissionCancellationStopsNextOwner(t *testing.T) {
	for _, stage := range []string{"workload", "verification", "session"} {
		t.Run(stage, func(t *testing.T) {
			parent, cancel := context.WithCancel(context.Background())
			defer cancel()
			var sessionCalls, handlerCalls atomic.Int64
			admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
				Verifier: testVerifier(t),
				Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
					if stage == "verification" {
						cancel()
					}
					return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
				},
				Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
					sessionCalls.Add(1)
					if stage == "session" {
						cancel()
						return nil, context.Canceled
					}
					return testRuntimeAuthorizingSessionState(testPrincipalID, 1), nil
				},
				State: testRuntimeSecurityState(t),
			})
			if err != nil {
				t.Fatal(err)
			}
			workload := runtimegrpc.VerifiedCaller(testWorkloadID)
			if stage == "workload" {
				cancel()
			}
			callErr := invokeSecurityChainWithContext(t, parent, admission, workload, testDelegationToken, 1, func(context.Context) {
				handlerCalls.Add(1)
			})
			if status.Code(callErr) != codes.Canceled || handlerCalls.Load() != 0 {
				t.Fatalf("error=%v handler calls=%d, want canceled/0", callErr, handlerCalls.Load())
			}
			if stage != "session" && sessionCalls.Load() != 0 {
				t.Fatalf("cancellation at %s reached session owner", stage)
			}
		})
	}
}

func TestSecurityAdmissionCancellationDuringSecurityStateStopsSession(t *testing.T) {
	parent, cancel := context.WithCancel(context.Background())
	defer cancel()
	now := time.Now()
	state, err := NewRuntimeSecurityState(context.Background(), RuntimeSecurityStateConfig{
		Now: func() time.Time { return now },
		Replica: func(context.Context) (RuntimeReplicaSecurityState, bool, error) {
			return RuntimeReplicaSecurityState{OrgID: testOrgID, RuntimeAudience: testRuntimeAudience, SecurityEpoch: 1, LeaseSecurityEpoch: 1, LeaseExpiresAt: now.Add(time.Minute)}, true, nil
		},
		Admission: func(context.Context, delegationv1.Claims) (RuntimeAdmissionSecurityState, error) {
			cancel()
			return RuntimeAdmissionSecurityState{}, context.Canceled
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	var sessionCalls, handlerCalls atomic.Int64
	admission, err := NewSecurityAdmission(SecurityAdmissionConfig{
		Verifier: testVerifier(t), State: state,
		Bindings: func(context.Context, runtimegrpc.VerifiedCaller) (RuntimeCallerBinding, bool, error) {
			return RuntimeCallerBinding{CallerWorkloadID: testWorkloadID}, true, nil
		},
		Sessions: func(context.Context, string, string) (*RuntimeSessionState, error) {
			sessionCalls.Add(1)
			return nil, nil
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	callErr := invokeSecurityChainWithContext(t, parent, admission, testWorkloadID, mustSignTestDelegation(testClaims(now)), 1, func(context.Context) { handlerCalls.Add(1) })
	if status.Code(callErr) != codes.Canceled || sessionCalls.Load() != 0 || handlerCalls.Load() != 0 {
		t.Fatalf("error=%v sessions=%d handler=%d", callErr, sessionCalls.Load(), handlerCalls.Load())
	}
	if !admission.Ready() {
		t.Fatal("request cancellation invalidated replica security readiness")
	}
}

func invokeSecurityChain(t *testing.T, admission *SecurityAdmission, workload runtimegrpc.VerifiedCaller, token string, metadataCount int, handler func(context.Context)) error {
	t.Helper()
	return invokeSecurityChainWithContext(t, context.Background(), admission, workload, token, metadataCount, handler)
}

func invokeSecurityChainWithContext(t *testing.T, parent context.Context, admission *SecurityAdmission, workload runtimegrpc.VerifiedCaller, token string, metadataCount int, handler func(context.Context)) error {
	t.Helper()
	values := []string{
		envelope.ProtocolMajorMetadataKey, strconv.FormatUint(uint64(semantic.ProtocolMajor), 10),
		envelope.ProtocolMinorMetadataKey, strconv.FormatUint(uint64(semantic.ProtocolMinor), 10),
		envelope.CapabilityMetadataKey, semantic.CapabilityName,
	}
	for range metadataCount {
		values = append(values, envelope.RuntimeDelegationMetadataKey, token)
	}
	ctx := metadata.NewIncomingContext(parent, metadata.Pairs(values...))
	ctx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	policy, err := runtimegrpc.NewPolicy(runtimegrpc.Config{
		Authority: func(context.Context, string) (runtimegrpc.VerifiedCaller, error) {
			if parent.Err() != nil {
				return "", parent.Err()
			}
			return workload, nil
		},
		AdmissionLimit: 1, AttemptCap: time.Second,
	})
	if err != nil {
		t.Fatal(err)
	}
	info := &grpc.UnaryServerInfo{FullMethod: runtimev1.RecordsService_ReadSelectedRoot_FullMethodName}
	_, err = policy.UnaryServerInterceptor()(ctx, nil, info, func(ctx context.Context, request any) (any, error) {
		return admission.UnaryServerInterceptor()(ctx, request, info, func(ctx context.Context, _ any) (any, error) {
			handler(ctx)
			return struct{}{}, nil
		})
	})
	return err
}

func invokeWorkloadSecurityChain(t *testing.T, admission *SecurityAdmission, handler func(context.Context)) error {
	t.Helper()
	ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(
		envelope.ProtocolMajorMetadataKey, strconv.FormatUint(uint64(catalogsemantic.ProtocolMajor), 10),
		envelope.ProtocolMinorMetadataKey, strconv.FormatUint(uint64(catalogsemantic.ProtocolMinor), 10),
		envelope.CapabilityMetadataKey, catalogsemantic.AppMetadataCapabilityName,
	))
	ctx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	policy, err := runtimegrpc.NewPolicyWithOptions(runtimegrpc.Config{
		Authority: func(context.Context, string) (runtimegrpc.VerifiedCaller, error) {
			return runtimegrpc.VerifiedCaller(testWorkloadID), nil
		},
		AdmissionLimit: 1, AttemptCap: time.Second,
	}, runtimegrpc.WithPlatformCapabilityMaxAdmissionLease(
		catalogsemantic.AppMetadataCapabilityName, time.Second,
	), runtimegrpc.WithResourceClassAdmissionLimit(
		runtimegrpc.ResourceClassCatalogWatch, 1,
	))
	if err != nil {
		t.Fatal(err)
	}
	info := &grpc.UnaryServerInfo{FullMethod: catalogv1.ConsumerViewService_GetAppMetadataView_FullMethodName}
	_, err = policy.UnaryServerInterceptor()(ctx, nil, info, func(ctx context.Context, request any) (any, error) {
		return admission.UnaryServerInterceptor()(ctx, request, info, func(ctx context.Context, _ any) (any, error) {
			handler(ctx)
			return struct{}{}, nil
		})
	})
	return err
}

func TestSecurityAdmissionOwnerErrorsRemainDisclosureSafe(t *testing.T) {
	err := admissionOwnerError(context.Background(), errors.New("database exposed detail"))
	var failure *semantic.Failure
	if !errors.As(err, &failure) || failure.Category != semantic.FailureUnavailable || err.Error() == "database exposed detail" {
		t.Fatalf("owner error = %#v, want disclosure-safe unavailable", err)
	}
	if status.Code(mapping.ToStatusError(err)) != codes.Unavailable {
		t.Fatalf("status = %v", mapping.ToStatusError(err))
	}
}

func TestRecordsServerHasNoIdentityFallbackWhenInterceptorIsBypassed(t *testing.T) {
	reader := &readerStub{}
	server, err := NewRecordsServer(reader, ReceiptSourceFunc(BootstrapReceipts))
	if err != nil {
		t.Fatal(err)
	}
	response, callErr := server.ReadSelectedRoot(context.Background(), nil)
	if response != nil || failureCategoryForTest(callErr) != semantic.FailureUnauthenticated || reader.calls != 0 {
		t.Fatalf("response=%#v error=%v reader calls=%d, want unauthenticated/0", response, callErr, reader.calls)
	}
}
