package calls import ( "context" "crypto/hmac" "encoding/json" "errors" "net/http" "strings" access "amadan.net/oficina/agent-access.git" "amadan.net/oficina/home/connect/linkstore" "gorm.io/gorm" ) type delegatedBoundaryKey struct{} type delegatedRecheck func(context.Context, access.Principal) error func (a *app) delegatedBoundary(verifier access.Verifier, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { parts := strings.Fields(r.Header.Get("Authorization")) token := "" if len(parts) == 2 { token = parts[1] } check := delegatedRecheck(func(ctx context.Context, p access.Principal) error { current, e := verifier.Verify(ctx, token) if e != nil { return e } if current.Subject != p.Subject || current.Client != p.Client || current.Grant != p.Grant || !current.Allows(a.agentTeam, "calls:write") { return access.Fail("forbidden", "This connection is no longer authorized.") } return nil }) state := &delegatedResponseState{} ctx := context.WithValue(r.Context(), delegatedResponseKey{}, state) next.ServeHTTP(&delegatedLeaseWriter{ResponseWriter: w, state: state, team: a.cfg.Team != nil}, r.WithContext(context.WithValue(ctx, delegatedBoundaryKey{}, check))) }) } func (a *app) bindDelegated(tx *gorm.DB) error { raw, _ := json.Marshal([]string{a.cfg.Home.Issuer, a.agentIssuer, a.agentTeam}) want, e := a.sealer.Fingerprint("connection.authority.v1", string(raw)) if e != nil { return e } if e = tx.Exec("INSERT INTO calls_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM calls_agent_meetings) AND NOT EXISTS(SELECT 1 FROM calls_connections) AND NOT EXISTS(SELECT 1 FROM calls_agent_schedules) ON CONFLICT(id) DO NOTHING", want).Error; e != nil { return e } var got string if e = tx.Raw("SELECT keycheck FROM calls_agent_state WHERE id=1").Scan(&got).Error; e != nil { return e } if !hmac.Equal([]byte(got), []byte(want)) { return access.Fail("unavailable", "Agent receipt authority requires an explicit migration.") } return nil } func (a *app) checkDelegatedWriter(ctx context.Context, tx *gorm.DB, p access.Principal, expected Person) error { check, ok := ctx.Value(delegatedBoundaryKey{}).(delegatedRecheck) if !ok || check == nil { return access.Fail("forbidden", "Agent authority is unavailable.") } if e := check(ctx, p); e != nil { return e } person, e := a.home.bridge.ResolveOn(ctx, tx.Statement.ConnPool, p.Subject) if errors.Is(e, linkstore.ErrRefused) { return access.Fail("forbidden", "The linked identity is unavailable.") } if e != nil { return e } if person.ID != expected.ID || person.Label != expected.Email { return access.Fail("forbidden", "The linked identity changed.") } id := person.ID currentStore := *a.store currentStore.g = tx current, exists, e := currentStore.personByID(ctx, id) if e != nil { return e } if !exists || current.Email != expected.Email { return access.Fail("forbidden", "This account is no longer admitted.") } return a.delegatedStanding(ctx, p.Subject, current, false) }