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
3 changes: 2 additions & 1 deletion cmd/mecak8s/identity_broker_harness_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,8 @@ func TestIdentityBrokerAgainstOfflineHarness(t *testing.T) {
t.Errorf("register in the expired broker session = %v, want %v", err, closed)
}
if _, err := built.IdentityBroker.AuthorizeCall(t.Context(), identitybroker.AuthorizeCallRequest{
SessionID: expiring.ID, Credential: before.Credential, OperationID: "op-1", Target: "gateway", Tool: "search",
SessionID: expiring.ID, Credential: before.Credential, OperationID: "op-1", RunID: "R42", RunOwner: aliceCompany,
Method: identitybroker.MethodToolsCall, Server: "gateway", Tool: "search", ArgumentsSHA256: strings.Repeat("ab", 32),
}); !errors.Is(err, closed) {
t.Errorf("authorize in the expired broker session = %v, want %v", err, closed)
}
Expand Down
4 changes: 3 additions & 1 deletion cmd/mecak8s/identity_broker_real_as1_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"net/http"
"strings"
"sync/atomic"
"testing"
"time"
Expand Down Expand Up @@ -92,7 +93,8 @@ func TestIdentityBrokerAgainstRealAS1(t *testing.T) {
t.Errorf("register in the expired broker session = %v, want %v", err, closed)
}
if _, err := built.IdentityBroker.AuthorizeCall(t.Context(), identitybroker.AuthorizeCallRequest{
SessionID: expiring.ID, Credential: before.Credential, OperationID: "op-1", Target: "gateway", Tool: "search",
SessionID: expiring.ID, Credential: before.Credential, OperationID: "op-1", RunID: "R42", RunOwner: aliceCompany,
Method: identitybroker.MethodToolsCall, Server: "gateway", Tool: "search", ArgumentsSHA256: strings.Repeat("ab", 32),
}); !errors.Is(err, closed) {
t.Errorf("authorize in the expired broker session = %v, want %v", err, closed)
}
Expand Down
86 changes: 86 additions & 0 deletions internal/identitybroker/attempts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package identitybroker

import "slices"

// maxAttemptsPerSession bounds how many issued attempts a session's ledger
// keeps; the oldest is forgotten first, so a rejection report for it is
// refused.
const maxAttemptsPerSession = 1024

// callKey is what an attempt was issued for. A rejection report must repeat
// it exactly.
type callKey struct {
operationID, agent, method, server, tool, argumentsSHA256 string
}

// attemptLedger remembers the attempts AuthorizeCall issued, so a caller can
// report one rejected token and get one retry: per session, the issued
// attempts in issue order, at most maxAttemptsPerSession of them. An attempt
// issued by a retry is never added, so a second rejection fails the call. Its
// methods are guarded by sessionTable.mu.
//
// Shortcut: retry state held in memory, forgetting a session's oldest attempt beyond 1024; removed by #2563 (durable state).
type attemptLedger struct {
bySession map[string]*sessionAttempts
}

type sessionAttempts struct {
order []string // attempt IDs, oldest first
calls map[string]callKey
}

func newAttemptLedger() *attemptLedger {
return &attemptLedger{bySession: map[string]*sessionAttempts{}}
}

// issueLocked records attemptID as issued in sessionID for call.
func (m *attemptLedger) issueLocked(sessionID, attemptID string, call callKey) {
s, ok := m.bySession[sessionID]
if !ok {
s = &sessionAttempts{calls: map[string]callKey{}}
m.bySession[sessionID] = s
}
if _, ok := s.calls[attemptID]; ok {
return
}
if len(s.order) == maxAttemptsPerSession {
delete(s.calls, s.order[0])
s.order = slices.Delete(s.order, 0, 1)
}
s.order = append(s.order, attemptID)
s.calls[attemptID] = call
}

// knownLocked reports whether attemptID was issued in sessionID and not yet
// consumed. It does not compare the call: it runs before the credential
// identifies the agent, so consumeLocked checks the call.
func (m *attemptLedger) knownLocked(sessionID, attemptID string) bool {
s, ok := m.bySession[sessionID]
if !ok {
return false
}
_, ok = s.calls[attemptID]
return ok
}

// consumeLocked deletes attemptID and reports whether it was issued in
// sessionID for call. A mismatched call deletes it too, so an attempt is
// reported at most once whatever the report says.
func (m *attemptLedger) consumeLocked(sessionID, attemptID string, call callKey) bool {
s, ok := m.bySession[sessionID]
if !ok {
return false
}
issued, ok := s.calls[attemptID]
if !ok {
return false
}
delete(s.calls, attemptID)
s.order = slices.DeleteFunc(s.order, func(id string) bool { return id == attemptID })
return issued == call
}

// dropLocked forgets every attempt of sessionID.
func (m *attemptLedger) dropLocked(sessionID string) {
delete(m.bySession, sessionID)
}
90 changes: 90 additions & 0 deletions internal/identitybroker/attempts_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package identitybroker

import (
"context"
"fmt"
"testing"
)

var testCall = callKey{
operationID: "op-1", agent: "spiffe://agents.example.com/mecatl/agent/shared/inst/" + incMain,
method: MethodToolsCall, server: "github", tool: "github.pull_request_read",
argumentsSHA256: "abababababababababababababababababababababababababababababababab",
}

func TestMemoryAttemptsForgetTheOldestPastTheBound(t *testing.T) {
m := newAttemptLedger()
for i := range maxAttemptsPerSession + 1 {
m.issueLocked("bs_a", fmt.Sprintf("att_%d", i), testCall)
}
if m.knownLocked("bs_a", "att_0") {
t.Fatal("the oldest attempt is still known past the bound")
}
for _, id := range []string{"att_1", fmt.Sprintf("att_%d", maxAttemptsPerSession)} {
if !m.knownLocked("bs_a", id) {
t.Fatalf("attempt %s is not known", id)
}
}
if got := len(m.bySession["bs_a"].order); got != maxAttemptsPerSession {
t.Fatalf("the ledger keeps %d attempts, want %d", got, maxAttemptsPerSession)
}
}

func TestMemoryAttemptsAreConsumedOnce(t *testing.T) {
m := newAttemptLedger()
m.issueLocked("bs_a", "att_1", testCall)
if !m.knownLocked("bs_a", "att_1") || !m.consumeLocked("bs_a", "att_1", testCall) {
t.Fatal("an issued attempt is not consumed")
}
if m.knownLocked("bs_a", "att_1") || m.consumeLocked("bs_a", "att_1", testCall) {
t.Fatal("a consumed attempt is consumed again")
}
if m.knownLocked("bs_a", "att_never") || m.consumeLocked("bs_a", "att_never", testCall) {
t.Fatal("an attempt never issued is consumed")
}
}

func TestMemoryAttemptsMatchTheCall(t *testing.T) {
m := newAttemptLedger()
m.issueLocked("bs_a", "att_1", testCall)
if m.knownLocked("bs_b", "att_1") || m.consumeLocked("bs_b", "att_1", testCall) {
t.Fatal("another session consumed the attempt")
}
other := testCall
other.tool = "github.create_pull_request"
if m.consumeLocked("bs_a", "att_1", other) {
t.Fatal("a report for another call consumed the attempt")
}
// The mismatched report used the attempt up.
if m.consumeLocked("bs_a", "att_1", testCall) {
t.Fatal("the attempt is consumed after a mismatched report used it up")
}
}

func TestAttemptsAreDroppedWhenTheSessionCloses(t *testing.T) {
b, err := New(testConfig(), nil, testKey(t, "attempts"))
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
workload := Workload{Name: "system:serviceaccount:mecatl:mecak8s"}
owner := Owner{Issuer: "https://login.example.com", Subject: "alice-204"}
s, err := b.OpenSession(ctx, workload, OpenSessionRequest{HostSessionID: "hostS42", Incarnation: incMain, Owner: owner})
if err != nil {
t.Fatal(err)
}
b.sessions.mu.Lock()
b.sessions.attempts.issueLocked(s.ID, "att_1", testCall)
b.sessions.mu.Unlock()
if err := b.CloseSession(ctx, workload, CloseSessionRequest{SessionID: s.ID, Reason: ReasonSessionClosed}); err != nil {
t.Fatal(err)
}
b.sessions.mu.Lock()
defer b.sessions.mu.Unlock()
if b.sessions.attempts.knownLocked(s.ID, "att_1") {
t.Fatal("a closed session's attempt is still known")
}
if _, ok := b.sessions.attempts.bySession[s.ID]; ok {
t.Fatal("a closed session's ledger is kept")
}
}
97 changes: 97 additions & 0 deletions internal/identitybroker/authorize.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package identitybroker

import (
"context"
"errors"
"time"
)

// AuthorizeCall implements Core, in the order Service.AuthorizeCall
// documents. Every refusal after the session lookup is recorded.
func (b *Broker) AuthorizeCall(ctx context.Context, workload Workload, req AuthorizeCallRequest) (Authorization, error) {
if err := checkCall(workload, req); err != nil {
return Authorization{}, err
}
t := b.sessions
t.mu.Lock()
s, err := t.callSessionLocked(workload, req.SessionID)
if s == nil {
t.mu.Unlock()
return Authorization{}, err
}
rec := decisionRecord(t.now(), workload, s, req)
// The rejection report is checked before the grant, so a session without
// one still refuses a report it never issued.
if err == nil && req.RejectedAttemptID != "" && !t.attempts.knownLocked(s.ID, req.RejectedAttemptID) {
err = ReasonError(ReasonDenied, "the rejected attempt is unknown or already retried")
}
if err == nil {
_, err = grantForCallLocked(s)
}
t.mu.Unlock()
if err != nil {
return Authorization{}, b.refuse(ctx, rec, err)
}

// Check 3: the credential identifies an agent registered to this open
// session.
agent, err := b.VerifyCredential(ctx, VerifyCredentialRequest{SessionID: s.ID, Credential: req.Credential})
if err != nil {
return Authorization{}, b.refuse(ctx, rec, err)
}
rec.Agent, rec.AgentID = agent.Agent, agent.AgentID

// Shortcut: step (6) checks 4 and 5 (run and owner) and 7 (ceiling) accept their inputs; removed by #2557 (checks 4 and 5) and the authority work (docs/drafts/agent-identity/README.md, "Order of work") for check 7.

// Check 6: the gateway routes the server.
// Shortcut: check 6 matches the call's server, not the tool's route; removed by #2538 (gateway entries carry their routed tools, or the design moves the tool check to the vMCP).
if !b.gateway.routes(req.Server) {
return Authorization{}, b.refuse(ctx, rec, ReasonError(ReasonDenied, "no gateway routes the server"))
}

// A call that passes every check is still refused: the next change adds
// design steps (7) and (8), the per-call ID-JAG exchange at AS-1 and its
// redemption at AS-2 for the gateway token.
return Authorization{}, b.refuse(ctx, rec, ReasonError(ReasonDenied, "call authorization is not available yet"))
}

// grantForCallLocked returns the grant a call in s uses: the refresh token s
// holds. It fails with ReasonNoGrant when s holds none. It is the one place
// that decides which grant a call uses; scheduled runs (#2569) and the
// chained exchange change only this function. The caller holds t.mu.
func grantForCallLocked(s *brokerSession) (*heldGrant, error) {
if s.grant == nil {
return nil, ReasonError(ReasonNoGrant, "the broker session holds no refresh token")
}
return s.grant, nil
}

// decisionRecord returns the record of a decision on req in s, before any
// outcome. Its owner is the session's verified owner, or the reported one
// when the session has none. The caller holds t.mu.
func decisionRecord(now time.Time, workload Workload, s *brokerSession, req AuthorizeCallRequest) DecisionRecord {
owner := s.Owner
if s.verifiedOwner != nil {
owner = *s.verifiedOwner
}
return DecisionRecord{
At: now, SessionID: s.ID, Workload: workload, Owner: owner,
RunID: req.RunID, DelegationID: req.DelegationID, RunOwner: req.RunOwner,
OperationID: req.OperationID, RejectedAttemptID: req.RejectedAttemptID,
Method: req.Method, Server: req.Server, Tool: req.Tool, ArgumentsSHA256: req.ArgumentsSHA256,
}
}

// refuse records err as the refusal of rec's call and returns err. The
// refusal is recorded even when ctx is cancelled, as a cancelled call is
// still a decision.
func (b *Broker) refuse(ctx context.Context, rec DecisionRecord, err error) error {
rec.Code = CodeInternal
var e *Error
if errors.As(err, &e) {
rec.Code, rec.Reason = e.Code, e.Reason
}
rec.Outcome = outcomeFor(rec.Code)
b.recordDecision(context.WithoutCancel(ctx), rec)
return err
}
Loading
Loading