From 400d1b1678b73c3e3be6e48b84eab1bdd2863f63 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:39:56 +0100 Subject: [PATCH 1/2] feat(connections): connect two workspaces by code (#138) A workspace administrator creates a code (160 random bits, 14 days, single use, stored as SHA-256 only); another workspace's administrator enters it and the two are connected at once. Each side sees only the other's display name. Every code that does not work gets the same 404, and entering codes is limited to 20 per hour per workspace and person. Either side can end a connection; archiving a workspace ends all of its connections, and a purged side leaves the other an ended connection with the name it knew. Both audit logs record each step; the other side's entry names neither the person nor the address. Products read the active connections and check one before each delivery under the new route group connections.read (GET /v1/internal/tenants/{id}/connections, GET /v1/internal/connections/{connection}). The Postgres GetTenant now answers a non-UUID id as not found (404), as the memory store does, instead of a 500. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- internal/server/admin_lifecycle.go | 2 + internal/server/authz.go | 3 + internal/server/authz_test.go | 10 +- internal/server/connections.go | 423 ++++++++++++++++++++ internal/server/connections_scope_test.go | 54 +++ internal/server/connections_test.go | 395 ++++++++++++++++++ internal/server/licences_ci.go | 6 +- internal/server/members.go | 6 +- internal/server/openapi_test.go | 8 + internal/server/server.go | 14 +- internal/server/tenants.go | 4 + internal/store/connections.go | 64 +++ internal/store/memory.go | 4 + internal/store/memory_connections.go | 180 +++++++++ internal/store/postgres.go | 7 +- internal/store/postgres_connections.go | 245 ++++++++++++ internal/store/store.go | 28 ++ migrations/0032_tenant_connections.down.sql | 2 + migrations/0032_tenant_connections.up.sql | 41 ++ openapi.yaml | 197 +++++++++ 20 files changed, 1685 insertions(+), 8 deletions(-) create mode 100644 internal/server/connections.go create mode 100644 internal/server/connections_scope_test.go create mode 100644 internal/server/connections_test.go create mode 100644 internal/store/connections.go create mode 100644 internal/store/memory_connections.go create mode 100644 internal/store/postgres_connections.go create mode 100644 migrations/0032_tenant_connections.down.sql create mode 100644 migrations/0032_tenant_connections.up.sql diff --git a/internal/server/admin_lifecycle.go b/internal/server/admin_lifecycle.go index 4a809a7..894a937 100644 --- a/internal/server/admin_lifecycle.go +++ b/internal/server/admin_lifecycle.go @@ -170,6 +170,8 @@ func (s *Server) adminPurgeTenant(w http.ResponseWriter, r *http.Request) { return } + // Archiving ended its connections; this only catches a failure then. + s.endTenantConnections(ctx, t, "tenant_purged") if err := s.Store.DeleteTenant(ctx, t.ID); err != nil { if mapStoreError(w, err) { return diff --git a/internal/server/authz.go b/internal/server/authz.go index 5ccd0f1..c632eb5 100644 --- a/internal/server/authz.go +++ b/internal/server/authz.go @@ -83,6 +83,9 @@ func routeGroup(method, path string) string { return "erp" case strings.HasPrefix(path, "/v1/internal/module-users/"): return "module-users" + case strings.HasPrefix(path, "/v1/internal/tenants/"), strings.HasPrefix(path, "/v1/internal/connections/"): + // Connections between tenants (#138): what products deliver over. + return "connections.read" case strings.HasPrefix(path, "/v1/entitlements"): return "entitlements" case strings.HasPrefix(path, "/v1/catalog"): diff --git a/internal/server/authz_test.go b/internal/server/authz_test.go index 7a0a583..4bc9099 100644 --- a/internal/server/authz_test.go +++ b/internal/server/authz_test.go @@ -3,7 +3,7 @@ package server import "testing" func TestAuthzRules(t *testing.T) { - a := ParseAuthzRules(" portal-svc:tenants,catalog,api-keys,audit,users ; pruefwerk-svc:entitlements,tenants.read,api-keys.verify,audit.write; root:* ;broken") + a := ParseAuthzRules(" portal-svc:tenants,catalog,api-keys,audit,users ; pruefwerk-svc:entitlements,tenants.read,api-keys.verify,audit.write,connections.read; werkpilot-svc:tenants.read; root:* ;broken") cases := []struct { azp, method, path string want bool @@ -22,6 +22,14 @@ func TestAuthzRules(t *testing.T) { {"unknown", "GET", "/v1/catalog", false}, {"portal-svc", "GET", "/v1/authz/catalogue", false}, {"root", "GET", "/v1/authz/catalogue", true}, + // Connections (#138): products read the internal pair with their own + // group; tenants.read alone does not reach it. + {"pruefwerk-svc", "GET", "/v1/internal/tenants/t1/connections", true}, + {"pruefwerk-svc", "GET", "/v1/internal/connections/c1", true}, + {"werkpilot-svc", "GET", "/v1/internal/tenants/t1/connections", false}, + {"portal-svc", "GET", "/v1/internal/connections/c1", false}, + {"portal-svc", "POST", "/v1/tenants/t1/connections", true}, + {"pruefwerk-svc", "POST", "/v1/tenants/t1/connection-invites", false}, } for _, c := range cases { if got := a.Allowed(c.azp, routeGroup(c.method, c.path)); got != c.want { diff --git a/internal/server/connections.go b/internal/server/connections.go new file mode 100644 index 0000000..0a87da4 --- /dev/null +++ b/internal/server/connections.go @@ -0,0 +1,423 @@ +package server + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base32" + "errors" + "net/http" + "strings" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// Connections between tenants (0032, #138): one tenant creates a code, another +// enters it, and the two are connected at once. Products send their data over +// a connection (Prüfwerk's supplier SBOM releases first) and ask their own +// consent for it; the registry only knows who is connected to whom. +// +// For the portal, on behalf of a workspace administrator: +// +// POST /v1/tenants/{id}/connection-invites (tenants.write) → 201 {id, code, expires_at} +// GET /v1/tenants/{id}/connection-invites (tenants.read) open codes, never the code itself +// DELETE /v1/tenants/{id}/connection-invites/{invite} (tenants.write) withdraw an unused code +// POST /v1/tenants/{id}/connections {code} (tenants.write) → 201 {id, peer_name, created_at} +// GET /v1/tenants/{id}/connections (tenants.read) +// POST /v1/tenants/{id}/connections/{connection}/end (tenants.write) +// +// For products, with a service token (group connections.read): +// +// GET /v1/internal/tenants/{id}/connections?state=active → {items: [{id, peer_tenant_id, peer_name}]} +// GET /v1/internal/connections/{connection} → {active, tenant_ids: [a, b]} +// +// Rules (GDPR): no tenant can find or list another. Before a code is entered +// neither side learns anything about the other; after that each sees only +// the other's display name. A code is 160 random bits, works once and for +// connectionInviteTTL, and is stored as its SHA-256 only; every code that +// does not work gets the same 404. Entering codes is rate-limited per tenant +// and per person. Either side can end a connection; archiving a tenant ends +// all of its connections. Both tenants' audit logs record each step, and the +// entry in the other side's log names neither the person nor where the +// request came from. +// +// Who may: a user token needs IT_ADMIN or OWNER in its own tenant, as for +// the team (403 FORBIDDEN_ROLE). The portal calls as its service client for +// the administrators it allows, named in X-Portal-User-*. + +const ( + // connectionInviteTTL is how long a code works. + connectionInviteTTL = 14 * 24 * time.Hour + // maxOpenConnectionInvites bounds the codes a tenant can have open. + maxOpenConnectionInvites = 20 + // connectionRedeemRate is how many codes a tenant, and a person, may + // enter per hour, working or not. + connectionRedeemRate = 20 + // connectionCodeBytes is the code's entropy: 160 bits, 32 base32 letters. + connectionCodeBytes = 20 +) + +// connectionCodeEncoding writes codes without padding; they are shown in +// groups of four. +var connectionCodeEncoding = base32.StdEncoding.WithPadding(base32.NoPadding) + +// newConnectionCode returns a fresh code for display and the hash to store. +func newConnectionCode() (code string, hash []byte, err error) { + raw := make([]byte, connectionCodeBytes) + if _, err := rand.Read(raw); err != nil { + return "", nil, err + } + plain := connectionCodeEncoding.EncodeToString(raw) + groups := make([]string, 0, len(plain)/4) + for i := 0; i < len(plain); i += 4 { + groups = append(groups, plain[i:i+4]) + } + h := sha256.Sum256([]byte(plain)) + return strings.Join(groups, "-"), h[:], nil +} + +// connectionCodeHash hashes an entered code, ignoring case, spaces and +// dashes. ok is false when it cannot be a code at all. +func connectionCodeHash(entered string) (hash []byte, ok bool) { + plain := strings.Map(func(r rune) rune { + switch { + case r == '-' || r == ' ': + return -1 + case r >= 'a' && r <= 'z': + return r - 'a' + 'A' + } + return r + }, entered) + if len(plain) != connectionCodeEncoding.EncodedLen(connectionCodeBytes) { + return nil, false + } + if _, err := connectionCodeEncoding.DecodeString(plain); err != nil { + return nil, false + } + h := sha256.Sum256([]byte(plain)) + return h[:], true +} + +// connectionTenant resolves the tenant of a portal connection route: a user +// token needs a tenant-admin role and its own tenant. +func (s *Server) connectionTenant(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, bool) { + if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && !p.IsTenantAdmin() { + writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "connections require the IT_ADMIN or OWNER org role") + return nil, false + } + return s.tenantInScope(ctx, w, r) +} + +type connectionInviteResp struct { + ID string `json:"id"` + Code string `json:"code,omitempty"` + CreatedBy string `json:"created_by,omitempty"` + CreatedAt time.Time `json:"created_at"` + ExpiresAt time.Time `json:"expires_at"` +} + +type connectionResp struct { + ID string `json:"id"` + PeerName string `json:"peer_name"` + State string `json:"state"` // active | ended + CreatedAt time.Time `json:"created_at"` + EndedAt *time.Time `json:"ended_at,omitempty"` + EndedByUs bool `json:"ended_by_us"` +} + +func connectionView(c store.Connection, tenantID string) connectionResp { + _, name, _ := c.Peer(tenantID) + state := "ended" + if c.Active { + state = "active" + } + return connectionResp{ID: c.ID, PeerName: name, State: state, CreatedAt: c.CreatedAt, EndedAt: c.EndedAt, + EndedByUs: c.EndedBy != "" && c.EndedBy == tenantID} +} + +// createConnectionInvite is POST /v1/tenants/{id}/connection-invites. The +// code is in this answer only. +func (s *Server) createConnectionInvite(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.connectionTenant(ctx, w, r) + if !ok { + return + } + now := s.now() + open, err := s.Store.ListConnectionInvites(ctx, t.ID, now) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if len(open) >= maxOpenConnectionInvites { + writeError(w, http.StatusConflict, "too_many_invites", "withdraw an open code before creating another") + return + } + code, hash, err := newConnectionCode() + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", "no code could be generated") + return + } + actor := s.teamActor(r) + inv, err := s.Store.CreateConnectionInvite(ctx, store.ConnectionInvite{ + TenantID: t.ID, CodeHash: hash, CreatedBy: firstNonEmpty(actor.Email, actor.ID), ExpiresAt: now.Add(connectionInviteTTL), + }) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "connection.invite_created", TargetID: inv.ID, TargetType: "connection_invite", + ActorID: actor.ID, ActorName: actor.Email, ActorType: actor.Type, + Metadata: map[string]interface{}{"expires_at": inv.ExpiresAt}, + }) + writeJSON(w, http.StatusCreated, connectionInviteResp{ID: inv.ID, Code: code, CreatedBy: inv.CreatedBy, + CreatedAt: inv.CreatedAt, ExpiresAt: inv.ExpiresAt}) +} + +// listConnectionInvites is GET /v1/tenants/{id}/connection-invites (a {sub} +// of tenantSubresource): the open codes, oldest first, without the codes. +func (s *Server) listConnectionInvites(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.connectionTenant(ctx, w, r) + if !ok { + return + } + open, err := s.Store.ListConnectionInvites(ctx, t.ID, s.now()) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + items := make([]connectionInviteResp, 0, len(open)) + for _, i := range open { + items = append(items, connectionInviteResp{ID: i.ID, CreatedBy: i.CreatedBy, CreatedAt: i.CreatedAt, ExpiresAt: i.ExpiresAt}) + } + writeJSON(w, http.StatusOK, map[string]any{"items": items}) +} + +// deleteConnectionInvite is DELETE /v1/tenants/{id}/connection-invites/{invite}. +func (s *Server) deleteConnectionInvite(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.connectionTenant(ctx, w, r) + if !ok { + return + } + id := r.PathValue("invite") + if err := s.Store.DeleteConnectionInvite(ctx, t.ID, id); err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + actor := s.teamActor(r) + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "connection.invite_withdrawn", TargetID: id, TargetType: "connection_invite", + ActorID: actor.ID, ActorName: actor.Email, ActorType: actor.Type, + }) + w.WriteHeader(http.StatusNoContent) +} + +type redeemReq struct { + Code string `json:"code"` +} + +// redeemConnectionInvite is POST /v1/tenants/{id}/connections {code}. +func (s *Server) redeemConnectionInvite(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, 1024) + var in redeemReq + if !decodeJSON(w, r, &in) { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.connectionTenant(ctx, w, r) + if !ok { + return + } + actor := s.teamActor(r) + now := s.now() + // Both windows count every attempt, so neither a tenant nor one person + // can try codes faster than the rate. + tenantOK := s.connLimiter.allow("tenant:"+t.ID, now, connectionRedeemRate) + personOK := s.connLimiter.allow("person:"+firstNonEmpty(actor.ID, actor.Email, actor.Type), now, connectionRedeemRate) + if !tenantOK || !personOK { + w.Header().Set("Retry-After", "3600") + writeError(w, http.StatusTooManyRequests, "rate_limited", "too many codes entered; try again later") + return + } + hash, valid := connectionCodeHash(in.Code) + var c *store.Connection + err := store.ErrNotFound + if valid { + c, err = s.Store.RedeemConnectionInvite(ctx, hash, t.ID, now) + } + switch { + case errors.Is(err, store.ErrNotFound): + writeError(w, http.StatusNotFound, "invalid_code", "the code is not valid") + return + case errors.Is(err, store.ErrConflict): + writeError(w, http.StatusConflict, "already_connected", "the two workspaces are connected already") + return + case err != nil: + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + s.auditConnection(ctx, r, *c, t.ID, "connection.created", actor, nil) + writeJSON(w, http.StatusCreated, connectionView(*c, t.ID)) +} + +// listConnections is GET /v1/tenants/{id}/connections (a {sub} of +// tenantSubresource), newest first. +func (s *Server) listConnections(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.connectionTenant(ctx, w, r) + if !ok { + return + } + conns, err := s.Store.ListConnections(ctx, t.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + items := make([]connectionResp, 0, len(conns)) + for _, c := range conns { + items = append(items, connectionView(c, t.ID)) + } + writeJSON(w, http.StatusOK, map[string]any{"items": items}) +} + +// endConnection is POST /v1/tenants/{id}/connections/{connection}/end. Ending +// one that has ended already answers it unchanged. +func (s *Server) endConnection(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.connectionTenant(ctx, w, r) + if !ok { + return + } + c, ended, err := s.Store.EndConnection(ctx, t.ID, r.PathValue("connection"), s.now()) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if ended { + s.auditConnection(ctx, r, *c, t.ID, "connection.ended", s.teamActor(r), nil) + } + writeJSON(w, http.StatusOK, connectionView(*c, t.ID)) +} + +// auditConnection records action in both tenants' audit logs, each entry +// naming the other side by its display name. The entry of actingTenant +// names actor; the other side's names neither the person nor where the +// request came from (metadata by=peer). With actingTenant "" the registry +// acted, and both entries are system entries. +func (s *Server) auditConnection(ctx context.Context, r *http.Request, c store.Connection, actingTenant, action string, actor teamActor, meta map[string]interface{}) { + for _, side := range c.TenantIDs() { + _, peerName, _ := c.Peer(side) + ev := store.AuditEvent{TenantID: side, Action: action, TargetID: c.ID, TargetType: "connection", TargetName: peerName, Metadata: meta} + if side == actingTenant { + ev.ActorID, ev.ActorName, ev.ActorType = actor.ID, actor.Email, actor.Type + s.emitAudit(ctx, r, ev) + continue + } + if actingTenant != "" { + ev.Metadata = withEntry(meta, "by", "peer") + } + s.emitAudit(ctx, nil, ev) + } +} + +// withEntry returns a copy of meta with k set to v. +func withEntry(meta map[string]interface{}, k string, v interface{}) map[string]interface{} { + out := make(map[string]interface{}, len(meta)+1) + for mk, mv := range meta { + out[mk] = mv + } + out[k] = v + return out +} + +// endTenantConnections ends every open connection of a tenant that was +// archived (or is purged), recording it in both audit logs. A failure is +// logged loudly; the connections are inactive anyway, since a connection +// with an archived side is never active. +func (s *Server) endTenantConnections(ctx context.Context, t *store.Tenant, reason string) { + ended, err := s.Store.EndTenantConnections(ctx, t.ID, s.now()) + if err != nil { + s.Log.Error("ending a tenant's connections failed", "tenant_id", t.ID, "reason", reason, "err", err) + return + } + for _, c := range ended { + s.auditConnection(ctx, nil, c, "", "connection.ended", teamActor{}, map[string]interface{}{"reason": reason}) + } +} + +type productConnection struct { + ID string `json:"id"` + PeerTenantID string `json:"peer_tenant_id"` + PeerName string `json:"peer_name"` +} + +// internalTenantConnections is GET /v1/internal/tenants/{id}/connections +// ?state=active: the tenant's active connections with the peer's tenant id, +// for a product to deliver over. 404 for an unknown tenant. +func (s *Server) internalTenantConnections(w http.ResponseWriter, r *http.Request) { + if st := r.URL.Query().Get("state"); st != "" && st != "active" { + writeError(w, http.StatusBadRequest, "invalid_state", "state must be active") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, err := s.Store.GetTenant(ctx, r.PathValue("id")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + conns, err := s.Store.ListConnections(ctx, t.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + items := []productConnection{} + for _, c := range conns { + if !c.Active { + continue + } + peer, name, _ := c.Peer(t.ID) + items = append(items, productConnection{ID: c.ID, PeerTenantID: peer, PeerName: name}) + } + writeJSON(w, http.StatusOK, map[string]any{"items": items}) +} + +// checkConnection is GET /v1/internal/connections/{connection}: whether +// it is active and the tenants it joins. A product asks it before every +// delivery. 404 for an unknown id. +func (s *Server) checkConnection(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + c, err := s.Store.GetConnection(ctx, r.PathValue("connection")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"active": c.Active, "tenant_ids": c.TenantIDs()}) +} diff --git a/internal/server/connections_scope_test.go b/internal/server/connections_scope_test.go new file mode 100644 index 0000000..30b8a31 --- /dev/null +++ b/internal/server/connections_scope_test.go @@ -0,0 +1,54 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" +) + +// Only a workspace administrator may create, enter or end, and only in its +// own workspace; another workspace's administrator gets a 404. +func TestConnections_userRoles(t *testing.T) { + acme := "00000000-0000-0000-0000-000000000001" + routes := []struct{ method, path, body string }{ + {http.MethodPost, "/connection-invites", ""}, + {http.MethodGet, "/connection-invites", ""}, + {http.MethodPost, "/connections", `{"code":"AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA"}`}, + {http.MethodGet, "/connections", ""}, + } + cases := []struct { + name string + tenant string + roles []string + denied int + }{ + {"plain user", acme, []string{"USER"}, http.StatusForbidden}, + {"finance", acme, []string{"FINANCE"}, http.StatusForbidden}, + {"cxo", acme, []string{"CXO"}, http.StatusForbidden}, + {"another workspace's admin", "11111111-1111-1111-1111-111111111111", []string{"IT_ADMIN"}, http.StatusNotFound}, + } + for _, c := range cases { + for _, rt := range routes { + p := &authn.Principal{Subject: "u-1", ClientID: "portal", TenantID: c.tenant, OrgRoles: c.roles} + _, h, tenant := scopedServer(t, p) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(rt.method, "/v1/tenants/"+tenant.ID+rt.path, strings.NewReader(rt.body))) + if rr.Code != c.denied { + t.Errorf("%s %s %s: %d %s", c.name, rt.method, rt.path, rr.Code, rr.Body.String()) + } + } + } + + for _, role := range []string{"IT_ADMIN", "OWNER"} { + p := &authn.Principal{Subject: "u-1", ClientID: "portal", TenantID: acme, OrgRoles: []string{role}} + _, h, tenant := scopedServer(t, p) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/tenants/"+tenant.ID+"/connection-invites", nil)) + if rr.Code != http.StatusCreated { + t.Errorf("%s creates a code: %d %s", role, rr.Code, rr.Body.String()) + } + } +} diff --git a/internal/server/connections_test.go b/internal/server/connections_test.go new file mode 100644 index 0000000..a10f7f2 --- /dev/null +++ b/internal/server/connections_test.go @@ -0,0 +1,395 @@ +package server_test + +import ( + "context" + "encoding/json" + "net/http" + "regexp" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +type connItem struct { + ID string `json:"id"` + PeerName string `json:"peer_name"` + State string `json:"state"` + CreatedAt time.Time `json:"created_at"` + EndedAt *time.Time `json:"ended_at"` + EndedByUs bool `json:"ended_by_us"` +} + +type productConn struct { + ID string `json:"id"` + PeerTenantID string `json:"peer_tenant_id"` + PeerName string `json:"peer_name"` +} + +func decodeInto[T any](t *testing.T, raw []byte) T { + t.Helper() + var v T + if err := json.Unmarshal(raw, &v); err != nil { + t.Fatalf("decode %s: %v", raw, err) + } + return v +} + +// connHarness adds a second tenant, Beta GmbH, to h. +func connHarness(t *testing.T, h *testHarness) (a, b *store.Tenant) { + t.Helper() + b, err := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "beta", Name: "Beta GmbH", Plan: "professional"}) + if err != nil { + t.Fatal(err) + } + return h.tenant, b +} + +func (h *testHarness) newCode(tenantID string) (id, code string) { + h.t.Helper() + resp, raw := h.do("POST", "/v1/tenants/"+tenantID+"/connection-invites", nil) + if resp.StatusCode != http.StatusCreated { + h.t.Fatalf("create code: %d %s", resp.StatusCode, raw) + } + inv := decodeInto[struct { + ID, Code string + ExpiresAt time.Time `json:"expires_at"` + }](h.t, raw) + return inv.ID, inv.Code +} + +func (h *testHarness) redeem(tenantID, code string) (int, []byte) { + h.t.Helper() + resp, raw := h.do("POST", "/v1/tenants/"+tenantID+"/connections", map[string]string{"code": code}) + return resp.StatusCode, raw +} + +func (h *testHarness) connections(tenantID string) []connItem { + h.t.Helper() + resp, raw := h.do("GET", "/v1/tenants/"+tenantID+"/connections", nil) + if resp.StatusCode != http.StatusOK { + h.t.Fatalf("list: %d %s", resp.StatusCode, raw) + } + return decodeInto[struct{ Items []connItem }](h.t, raw).Items +} + +// productConnections is what Prüfwerk's agent reads: the items key and the +// three fields are its contract (compliance-agent registry.rs). +func (h *testHarness) productConnections(tenantID string) []productConn { + h.t.Helper() + resp, raw := h.do("GET", "/v1/internal/tenants/"+tenantID+"/connections?state=active", nil) + if resp.StatusCode != http.StatusOK { + h.t.Fatalf("internal list: %d %s", resp.StatusCode, raw) + } + var page map[string][]productConn + if err := json.Unmarshal(raw, &page); err != nil || page["items"] == nil { + h.t.Fatalf("internal list is {items: [...]}: %s %v", raw, err) + } + return page["items"] +} + +func (h *testHarness) checkConnection(id string) (int, struct { + Active bool `json:"active"` + TenantIDs []string `json:"tenant_ids"` +}) { + h.t.Helper() + resp, raw := h.do("GET", "/v1/internal/connections/"+id, nil) + var out struct { + Active bool `json:"active"` + TenantIDs []string `json:"tenant_ids"` + } + if resp.StatusCode == http.StatusOK { + out = decodeInto[struct { + Active bool `json:"active"` + TenantIDs []string `json:"tenant_ids"` + }](h.t, raw) + } + return resp.StatusCode, out +} + +func (h *testHarness) audit(tenantID, action string) []store.AuditEvent { + h.t.Helper() + rows, _, err := h.store.ListAudit(context.Background(), store.AuditFilter{TenantID: tenantID, Action: action, Limit: 50}) + if err != nil { + h.t.Fatal(err) + } + return rows +} + +var codeShape = regexp.MustCompile(`^[A-Z2-7]{4}(-[A-Z2-7]{4}){7}$`) + +// Two tenants connect by code, see each other's display name only, and a +// product sees the peer's id; either side can end it. +func TestConnections_codeConnectsTwoTenants(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + a, b := connHarness(t, h) + inviteID, code := h.newCode(a.ID) + if !codeShape.MatchString(code) { + t.Fatalf("code shape: %q", code) + } + resp, raw := h.do("GET", "/v1/tenants/"+a.ID+"/connection-invites", nil) + open := decodeInto[struct { + Items []map[string]any + }](t, raw) + if resp.StatusCode != http.StatusOK || len(open.Items) != 1 || open.Items[0]["id"] != inviteID || open.Items[0]["code"] != nil { + t.Fatalf("open codes, without the code: %d %s", resp.StatusCode, raw) + } + + // Case, spaces and dashes do not matter. + status, raw := h.redeem(b.ID, " "+lower(code)+" ") + if status != http.StatusCreated { + t.Fatalf("redeem: %d %s", status, raw) + } + created := decodeInto[connItem](t, raw) + if created.PeerName != "Acme Inc." || created.State != "active" { + t.Fatalf("created: %+v", created) + } + if got := h.connections(a.ID); len(got) != 1 || got[0].PeerName != "Beta GmbH" || got[0].State != "active" || got[0].ID != created.ID { + t.Fatalf("issuer's list: %+v", got) + } + if got := h.productConnections(a.ID); len(got) != 1 || got[0].PeerTenantID != b.ID || got[0].PeerName != "Beta GmbH" { + t.Fatalf("product list: %+v", got) + } + if status, c := h.checkConnection(created.ID); status != http.StatusOK || !c.Active || len(c.TenantIDs) != 2 { + t.Fatalf("check: %d %+v", status, c) + } + resp, raw = h.do("GET", "/v1/tenants/"+a.ID+"/connection-invites", nil) + if resp.StatusCode != http.StatusOK || len(decodeInto[struct{ Items []any }](t, raw).Items) != 0 { + t.Fatalf("a used code is not open: %s", raw) + } + + // Connected already: 409, and the new code stays open. + _, again := h.newCode(a.ID) + if status, raw := h.redeem(b.ID, again); status != http.StatusConflict { + t.Fatalf("already connected: %d %s", status, raw) + } + + // B ends it; once is enough. + resp, raw = h.do("POST", "/v1/tenants/"+b.ID+"/connections/"+created.ID+"/end", nil) + ended := decodeInto[connItem](t, raw) + if resp.StatusCode != http.StatusOK || ended.State != "ended" || !ended.EndedByUs || ended.EndedAt == nil { + t.Fatalf("end: %d %s", resp.StatusCode, raw) + } + if resp, raw := h.do("POST", "/v1/tenants/"+b.ID+"/connections/"+created.ID+"/end", nil); resp.StatusCode != http.StatusOK { + t.Fatalf("end again: %d %s", resp.StatusCode, raw) + } + if got := h.connections(a.ID); got[0].State != "ended" || got[0].EndedByUs { + t.Fatalf("issuer sees it ended by the other side: %+v", got) + } + if got := h.productConnections(a.ID); len(got) != 0 { + t.Fatalf("an ended connection is not delivered over: %+v", got) + } + if status, c := h.checkConnection(created.ID); status != http.StatusOK || c.Active { + t.Fatalf("check after end: %d %+v", status, c) + } + if n := len(h.audit(a.ID, "connection.ended")) + len(h.audit(b.ID, "connection.ended")); n != 2 { + t.Fatalf("one end, one entry per side: %d", n) + } + + // The code left open connects them again. + if status, raw := h.redeem(b.ID, again); status != http.StatusCreated { + t.Fatalf("reconnect: %d %s", status, raw) + } + if got := h.connections(b.ID); len(got) != 2 || got[0].State != "active" || got[1].State != "ended" { + t.Fatalf("newest first: %+v", got) + } + + // A tenant that is no side cannot end it. + c, _ := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "gamma", Name: "Gamma AG", Plan: "professional"}) + if resp, raw := h.do("POST", "/v1/tenants/"+c.ID+"/connections/"+created.ID+"/end", nil); resp.StatusCode != http.StatusNotFound { + t.Fatalf("not a side: %d %s", resp.StatusCode, raw) + } + }) +} + +func lower(s string) string { + out := []byte(s) + for i, c := range out { + if c >= 'A' && c <= 'Z' { + out[i] = c - 'A' + 'a' + } + } + return string(out) +} + +// Every code that does not work gets the same answer. +func TestConnections_invalidCodesLookAlike(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + a, b := connHarness(t, h) + start := time.Now().UTC() + h.app.Now = func() time.Time { return start } + + _, used := h.newCode(a.ID) + if status, raw := h.redeem(b.ID, used); status != http.StatusCreated { + t.Fatalf("redeem: %d %s", status, raw) + } + _, own := h.newCode(b.ID) + _, expired := h.newCode(b.ID) + withdrawnID, withdrawn := h.newCode(b.ID) + if resp, raw := h.do("DELETE", "/v1/tenants/"+b.ID+"/connection-invites/"+withdrawnID, nil); resp.StatusCode != http.StatusNoContent { + t.Fatalf("withdraw: %d %s", resp.StatusCode, raw) + } + if resp, _ := h.do("DELETE", "/v1/tenants/"+b.ID+"/connection-invites/"+withdrawnID, nil); resp.StatusCode != http.StatusNotFound { + t.Fatalf("withdraw twice: %d", resp.StatusCode) + } + + c, _ := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "gamma", Name: "Gamma AG", Plan: "professional"}) + later := start.Add(15 * 24 * time.Hour) + var first []byte + for _, tc := range []struct { + name, code, tenant string + at time.Time + }{ + {"used", used, c.ID, start}, + {"own", own, b.ID, start}, + {"withdrawn", withdrawn, c.ID, start}, + {"unknown", "AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA", c.ID, start}, + {"garbage", "not a code", c.ID, start}, + {"empty", "", c.ID, start}, + {"expired", expired, c.ID, later}, + } { + h.app.Now = func() time.Time { return tc.at } + status, raw := h.redeem(tc.tenant, tc.code) + if status != http.StatusNotFound { + t.Fatalf("%s: %d %s", tc.name, status, raw) + } + if first == nil { + first = raw + } else if string(raw) != string(first) { + t.Fatalf("%s answers differently: %s vs %s", tc.name, raw, first) + } + } + // The expired code was open until then. + h.app.Now = func() time.Time { return start } + if status, raw := h.redeem(c.ID, expired); status != http.StatusCreated { + t.Fatalf("before expiry: %d %s", status, raw) + } + }) +} + +// Archiving a tenant ends its connections in both audit logs; purging it +// leaves the other side an ended connection with the name it knew. +func TestConnections_archiveAndPurgeEndThem(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + a, b := connHarness(t, h) + _, code := h.newCode(a.ID) + status, raw := h.redeem(b.ID, code) + if status != http.StatusCreated { + t.Fatalf("redeem: %d %s", status, raw) + } + conn := decodeInto[connItem](t, raw) + + // The entry in the issuer's log names neither person nor address. + peerEntries := h.audit(a.ID, "connection.created") + ownEntries := h.audit(b.ID, "connection.created") + if len(peerEntries) != 1 || len(ownEntries) != 1 { + t.Fatalf("created: %d %d", len(peerEntries), len(ownEntries)) + } + if e := peerEntries[0]; e.TargetName != "Beta GmbH" || e.SourceIP != "" || e.UserAgent != "" || e.ActorID != "" || e.Metadata["by"] != "peer" { + t.Fatalf("peer entry: %+v", e) + } + if e := ownEntries[0]; e.TargetName != "Acme Inc." || e.SourceIP == "" { + t.Fatalf("own entry: %+v", e) + } + + if resp, raw := h.do("POST", "/v1/tenants/"+b.ID+"/status", map[string]string{"status": "archived"}); resp.StatusCode != http.StatusOK { + t.Fatalf("archive: %d %s", resp.StatusCode, raw) + } + if got := h.connections(a.ID); got[0].State != "ended" || got[0].EndedByUs || got[0].EndedAt == nil { + t.Fatalf("archived peer: %+v", got) + } + if got := h.productConnections(a.ID); len(got) != 0 { + t.Fatalf("no delivery to an archived tenant: %+v", got) + } + for _, tenant := range []string{a.ID, b.ID} { + ev := h.audit(tenant, "connection.ended") + if len(ev) != 1 || ev[0].Metadata["reason"] != "tenant_archived" || ev[0].ActorType != "system" { + t.Fatalf("archive entries of %s: %+v", tenant, ev) + } + } + // An archived tenant's codes no longer work either. + _, late := h.newCode(b.ID) + if status, raw := h.redeem(a.ID, late); status != http.StatusNotFound { + t.Fatalf("archived issuer: %d %s", status, raw) + } + + if resp, raw := h.do("DELETE", "/v1/admin/tenants/"+b.ID+"?confirm=beta", nil); resp.StatusCode != http.StatusOK { + t.Fatalf("purge: %d %s", resp.StatusCode, raw) + } + if got := h.connections(a.ID); len(got) != 1 || got[0].PeerName != "Beta GmbH" || got[0].State != "ended" { + t.Fatalf("after purge: %+v", got) + } + if status, c := h.checkConnection(conn.ID); status != http.StatusOK || c.Active || len(c.TenantIDs) != 1 || c.TenantIDs[0] != a.ID { + t.Fatalf("check after purge: %d %+v", status, c) + } + }) +} + +// Unknown ids are 404 for products, and the list takes state=active only. +func TestConnections_productRoutes(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + for _, path := range []string{ + "/v1/internal/connections/no-uuid", + "/v1/internal/connections/00000000-0000-0000-0000-0000000000ff", + "/v1/internal/tenants/00000000-0000-0000-0000-0000000000ff/connections?state=active", + "/v1/internal/tenants/no-uuid/connections?state=active", + } { + if resp, raw := h.do("GET", path, nil); resp.StatusCode != http.StatusNotFound { + t.Errorf("%s: %d %s", path, resp.StatusCode, raw) + } + } + if resp, _ := h.do("GET", "/v1/internal/tenants/"+h.tenant.ID+"/connections?state=ended", nil); resp.StatusCode != http.StatusBadRequest { + t.Errorf("state=ended: %d", resp.StatusCode) + } + if got := h.productConnections(h.tenant.ID); len(got) != 0 { + t.Errorf("none yet: %+v", got) + } + }) +} + +// Entering codes is limited per tenant, working or not. +func TestConnections_redeemRateLimit(t *testing.T) { + h := newMemoryHarness(t) + defer h.Close() + _, b := connHarness(t, h) + for i := 0; i < 20; i++ { + if status, raw := h.redeem(b.ID, "AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA"); status != http.StatusNotFound { + t.Fatalf("attempt %d: %d %s", i, status, raw) + } + } + if status, raw := h.redeem(b.ID, "AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA"); status != http.StatusTooManyRequests { + t.Fatalf("21st attempt: %d %s", status, raw) + } + // Another tenant has its own window, but the same caller does not: + // without a principal every request is the same caller here. + c, _ := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "gamma", Name: "Gamma AG", Plan: "professional"}) + if status, _ := h.redeem(c.ID, "x"); status != http.StatusTooManyRequests { + t.Fatalf("per caller: %d", status) + } +} + +// Two workspaces entering one code at the same time: exactly one connects. +func TestConnections_aCodeWorksOnceUnderRace(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + a, b := connHarness(t, h) + c, _ := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "gamma", Name: "Gamma AG", Plan: "professional"}) + _, code := h.newCode(a.ID) + codes := make(chan int, 2) + for _, tenant := range []string{b.ID, c.ID} { + go func() { + status, _ := h.redeem(tenant, code) + codes <- status + }() + } + got := map[int]int{} + for range 2 { + got[<-codes]++ + } + if got[http.StatusCreated] != 1 || got[http.StatusNotFound] != 1 { + t.Fatalf("one connects, one is refused: %v", got) + } + if n := len(h.connections(a.ID)); n != 1 { + t.Fatalf("issuer has one connection: %d", n) + } + }) +} diff --git a/internal/server/licences_ci.go b/internal/server/licences_ci.go index 8b4bd13..e3d0a42 100644 --- a/internal/server/licences_ci.go +++ b/internal/server/licences_ci.go @@ -98,7 +98,7 @@ func (s *Server) issueCILicence(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusForbidden, "scope_missing", "the key needs scope "+need+" and the tenant a booking of "+in.Product) return } - if !s.ciLimiter.allow(k.ID, now) { + if !s.ciLimiter.allow(k.ID, now, ciLicenceRate) { writeError(w, http.StatusTooManyRequests, "rate_limited", "at most 60 CI licences per key and hour") return } @@ -190,7 +190,7 @@ type keyRateLimiter struct { hits map[string][]time.Time } -func (l *keyRateLimiter) allow(key string, now time.Time) bool { +func (l *keyRateLimiter) allow(key string, now time.Time, limit int) bool { l.mu.Lock() defer l.mu.Unlock() if l.hits == nil { @@ -203,7 +203,7 @@ func (l *keyRateLimiter) allow(key string, now time.Time) bool { kept = append(kept, t) } } - if len(kept) >= ciLicenceRate { + if len(kept) >= limit { l.hits[key] = kept return false } diff --git a/internal/server/members.go b/internal/server/members.go index 4029924..6f51342 100644 --- a/internal/server/members.go +++ b/internal/server/members.go @@ -70,7 +70,7 @@ func (s *Server) tenantInScope(ctx context.Context, w http.ResponseWriter, r *ht var tenantSubresources = []string{ "members", "documents", "projects", "contracts", "managed-services", "company-profile", "role-dataset", "store", - "module-users", + "module-users", "connections", "connection-invites", } // tenantSubresource dispatches GET /v1/tenants/{id}/{sub}. Only the members @@ -98,6 +98,10 @@ func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) { s.listCapabilityRequests(w, r) case "module-users": s.tenantModuleUsers(w, r) + case "connections": + s.listConnections(w, r) + case "connection-invites": + s.listConnectionInvites(w, r) default: writeError(w, http.StatusNotFound, "not_found", "no such tenant sub-resource") } diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index 6c0011e..3b05e94 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -53,6 +53,14 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1/capabilities"}, {"DELETE", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1/capabilities/portal:billing.view"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/capability-requests"}, + {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/connection-invites"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/connection-invites"}, + {"DELETE", "/v1/tenants/00000000-0000-0000-0000-000000000001/connection-invites/00000000-0000-0000-0000-000000000002"}, + {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/connections"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/connections"}, + {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/connections/00000000-0000-0000-0000-000000000002/end"}, + {"GET", "/v1/internal/tenants/00000000-0000-0000-0000-000000000001/connections?state=active"}, + {"GET", "/v1/internal/connections/00000000-0000-0000-0000-000000000002"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/capability-requests/00000000-0000-0000-0000-000000000002/approve"}, {"DELETE", "/v1/tenants/00000000-0000-0000-0000-000000000001/capability-requests/00000000-0000-0000-0000-000000000002"}, {"PUT", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset"}, diff --git a/internal/server/server.go b/internal/server/server.go index 78bd870..52b87be 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -53,8 +53,9 @@ type Server struct { // ones (contractdocs.Default). Tests pass their own. Contracts *contractdocs.Catalogue - blocks blockCache // MemberBlocked answers for user tokens (team.go) - ciLimiter keyRateLimiter // CI licence issues per API key (licences_ci.go) + blocks blockCache // MemberBlocked answers for user tokens (team.go) + ciLimiter keyRateLimiter // CI licence issues per API key (licences_ci.go) + connLimiter keyRateLimiter // codes entered per tenant and person (connections.go) } func (s *Server) now() time.Time { @@ -183,6 +184,15 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("GET /v1/tenants/{id}/products/pruefwerk/settings", s.getPruefwerkSettings) mux.HandleFunc("PUT /v1/tenants/{id}/products/pruefwerk/settings", s.putPruefwerkSettings) + // Connections between tenants (0032, #138): the two lists are {sub}s of + // tenantSubresource; products read the internal pair (connections.read). + mux.HandleFunc("POST /v1/tenants/{id}/connection-invites", s.createConnectionInvite) + mux.HandleFunc("DELETE /v1/tenants/{id}/connection-invites/{invite}", s.deleteConnectionInvite) + mux.HandleFunc("POST /v1/tenants/{id}/connections", s.redeemConnectionInvite) + mux.HandleFunc("POST /v1/tenants/{id}/connections/{connection}/end", s.endConnection) + mux.HandleFunc("GET /v1/internal/tenants/{id}/connections", s.internalTenantConnections) + mux.HandleFunc("GET /v1/internal/connections/{connection}", s.checkConnection) + // entitlements mux.HandleFunc("GET /v1/entitlements", s.listTenantProducts) mux.HandleFunc("POST /v1/internal/entitlements/check", s.checkEntitlement) diff --git a/internal/server/tenants.go b/internal/server/tenants.go index 275f7d8..0a5ee4a 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -423,6 +423,10 @@ func (s *Server) setTenantStatus(w http.ResponseWriter, r *http.Request) { // the tenant's Keycloak organization (ERP/02: Keycloak carries only the // coarse flag). Best-effort; failures are audited, never returned. func (s *Server) syncTenantStatus(ctx context.Context, r *http.Request, t *store.Tenant) { + // Every status change passes here: an archived tenant's connections end. + if t.Status == store.StatusArchived { + s.endTenantConnections(ctx, t, "tenant_archived") + } if err := s.Keycloak.SyncTenantStatus(ctx, t.Slug, t.Status); err != nil { s.Log.Warn("keycloak status sync failed", "tenant_id", t.ID, "status", t.Status, "err", err) s.emitAudit(ctx, r, store.AuditEvent{ diff --git a/internal/store/connections.go b/internal/store/connections.go new file mode 100644 index 0000000..1c27849 --- /dev/null +++ b/internal/store/connections.go @@ -0,0 +1,64 @@ +package store + +import "time" + +// ConnectionInvite is a code one tenant creates so that another can connect +// to it (0032, #138). Only the code's SHA-256 is kept. +type ConnectionInvite struct { + ID string `json:"id"` + TenantID string `json:"tenant_id"` + CodeHash []byte `json:"-"` + CreatedBy string `json:"created_by"` + CreatedAt time.Time `json:"created_at"` + ExpiresAt time.Time `json:"expires_at"` + UsedAt *time.Time `json:"used_at,omitempty"` +} + +func (i ConnectionInvite) valid() bool { + return i.TenantID != "" && len(i.CodeHash) == 32 && len(i.CreatedBy) <= 320 && !i.ExpiresAt.IsZero() +} + +// Connection joins two tenants (0032, #138): TenantA created the code, +// TenantB redeemed it. A side whose tenant was purged has an empty id; its +// name is then the one it had when the two connected, otherwise the +// tenant's current name. +type Connection struct { + ID string `json:"id"` + TenantA string `json:"tenant_a"` + TenantB string `json:"tenant_b"` + NameA string `json:"name_a"` + NameB string `json:"name_b"` + CreatedAt time.Time `json:"created_at"` + EndedAt *time.Time `json:"ended_at,omitempty"` + // EndedBy is the tenant that ended it; empty when it is open or the + // registry ended it (a tenant archived). + EndedBy string `json:"ended_by,omitempty"` + // Active: not ended, and both tenants exist and are not archived. Data + // may be sent over an active connection only. + Active bool `json:"active"` +} + +// Peer is the side of c opposite tenant: its id ("" once purged) and +// display name. ok is false when tenant is not a side of c. +func (c Connection) Peer(tenant string) (id, name string, ok bool) { + switch { + case tenant == "": + return "", "", false + case c.TenantA == tenant: + return c.TenantB, c.NameB, true + case c.TenantB == tenant: + return c.TenantA, c.NameA, true + } + return "", "", false +} + +// TenantIDs are the sides of c that still exist. +func (c Connection) TenantIDs() []string { + out := make([]string, 0, 2) + for _, id := range []string{c.TenantA, c.TenantB} { + if id != "" { + out = append(out, id) + } + } + return out +} diff --git a/internal/store/memory.go b/internal/store/memory.go index 28328f4..5ca4395 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -59,6 +59,9 @@ type Memory struct { capRequests []CapabilityRequest // pending four-eyes grants, oldest first (0029) + connInvites []ConnectionInvite // connection codes, oldest first (0032) + connections []Connection // stored sides, snapshot names and end; oldest first (0032) + moduleDays map[moduleDayKey]int // Managed Git daily counts (0031) moduleSeen map[moduleSeenKey]time.Time // licence users per month (0031) → first seen } @@ -627,6 +630,7 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error { m.contractDocs = kept m.deleteIntake(id) m.capRequests = slices.DeleteFunc(m.capRequests, func(r CapabilityRequest) bool { return r.TenantID == id }) + m.deleteConnections(id) m.deleteModuleUsers(id) for kid, k := range m.apiKeys { if k.TenantID == id { diff --git a/internal/store/memory_connections.go b/internal/store/memory_connections.go new file mode 100644 index 0000000..86c6413 --- /dev/null +++ b/internal/store/memory_connections.go @@ -0,0 +1,180 @@ +package store + +import ( + "bytes" + "context" + "slices" + "time" + + "github.com/google/uuid" +) + +// connView is c as read: current names of the sides that exist, and +// whether it is active. The caller holds m.mu. +func (m *Memory) connView(c Connection) Connection { + active := c.EndedAt == nil + for _, side := range []struct { + id string + name *string + }{{c.TenantA, &c.NameA}, {c.TenantB, &c.NameB}} { + t, ok := m.tenants[side.id] + if !ok { + active = false + continue + } + *side.name = t.Name + if t.Status == StatusArchived { + active = false + } + } + c.Active = active + return c +} + +func (m *Memory) CreateConnectionInvite(_ context.Context, inv ConnectionInvite) (*ConnectionInvite, error) { + if !inv.valid() { + return nil, ErrInvalidInput + } + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.tenants[inv.TenantID]; !ok { + return nil, ErrNotFound + } + if slices.ContainsFunc(m.connInvites, func(i ConnectionInvite) bool { return bytes.Equal(i.CodeHash, inv.CodeHash) }) { + return nil, ErrConflict + } + inv.ID = uuid.NewString() + inv.CreatedAt = time.Now().UTC().Truncate(time.Microsecond) + inv.UsedAt = nil + m.connInvites = append(m.connInvites, inv) + return &inv, nil +} + +func (m *Memory) ListConnectionInvites(_ context.Context, tenantID string, now time.Time) ([]ConnectionInvite, error) { + m.mu.RLock() + defer m.mu.RUnlock() + out := []ConnectionInvite{} + for _, i := range m.connInvites { + if i.TenantID == tenantID && i.UsedAt == nil && now.Before(i.ExpiresAt) { + out = append(out, i) + } + } + return out, nil +} + +func (m *Memory) DeleteConnectionInvite(_ context.Context, tenantID, id string) error { + m.mu.Lock() + defer m.mu.Unlock() + n := len(m.connInvites) + m.connInvites = slices.DeleteFunc(m.connInvites, func(i ConnectionInvite) bool { + return i.TenantID == tenantID && i.ID == id && i.UsedAt == nil + }) + if len(m.connInvites) == n { + return ErrNotFound + } + return nil +} + +func (m *Memory) RedeemConnectionInvite(_ context.Context, codeHash []byte, tenantID string, now time.Time) (*Connection, error) { + m.mu.Lock() + defer m.mu.Unlock() + at := slices.IndexFunc(m.connInvites, func(i ConnectionInvite) bool { return bytes.Equal(i.CodeHash, codeHash) }) + if at < 0 { + return nil, ErrNotFound + } + inv := &m.connInvites[at] + issuer, okA := m.tenants[inv.TenantID] + redeemer, okB := m.tenants[tenantID] + if inv.UsedAt != nil || !now.Before(inv.ExpiresAt) || !okA || !okB || issuer.ID == redeemer.ID || + issuer.Status == StatusArchived || redeemer.Status == StatusArchived { + return nil, ErrNotFound + } + if slices.ContainsFunc(m.connections, func(c Connection) bool { + return c.EndedAt == nil && ((c.TenantA == issuer.ID && c.TenantB == redeemer.ID) || (c.TenantA == redeemer.ID && c.TenantB == issuer.ID)) + }) { + return nil, ErrConflict + } + used := now.UTC() + inv.UsedAt = &used + c := Connection{ + ID: uuid.NewString(), TenantA: issuer.ID, TenantB: redeemer.ID, NameA: issuer.Name, NameB: redeemer.Name, + CreatedAt: now.UTC().Truncate(time.Microsecond), + } + m.connections = append(m.connections, c) + v := m.connView(c) + return &v, nil +} + +func (m *Memory) ListConnections(_ context.Context, tenantID string) ([]Connection, error) { + m.mu.RLock() + defer m.mu.RUnlock() + out := []Connection{} + for i := len(m.connections) - 1; i >= 0; i-- { + if c := m.connections[i]; tenantID != "" && (c.TenantA == tenantID || c.TenantB == tenantID) { + out = append(out, m.connView(c)) + } + } + return out, nil +} + +func (m *Memory) GetConnection(_ context.Context, id string) (*Connection, error) { + m.mu.RLock() + defer m.mu.RUnlock() + for _, c := range m.connections { + if c.ID == id { + v := m.connView(c) + return &v, nil + } + } + return nil, ErrNotFound +} + +func (m *Memory) EndConnection(_ context.Context, tenantID, id string, at time.Time) (*Connection, bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + for i := range m.connections { + c := &m.connections[i] + if c.ID != id || tenantID == "" || (c.TenantA != tenantID && c.TenantB != tenantID) { + continue + } + ended := c.EndedAt == nil + if ended { + t := at.UTC().Truncate(time.Microsecond) + c.EndedAt, c.EndedBy = &t, tenantID + } + v := m.connView(*c) + return &v, ended, nil + } + return nil, false, ErrNotFound +} + +func (m *Memory) EndTenantConnections(_ context.Context, tenantID string, at time.Time) ([]Connection, error) { + m.mu.Lock() + defer m.mu.Unlock() + out := []Connection{} + t := at.UTC().Truncate(time.Microsecond) + for i := range m.connections { + c := &m.connections[i] + if c.EndedAt == nil && tenantID != "" && (c.TenantA == tenantID || c.TenantB == tenantID) { + c.EndedAt = &t + out = append(out, m.connView(*c)) + } + } + return out, nil +} + +// deleteConnections drops a purged tenant's codes and clears its side of +// its connections, as the foreign keys do in Postgres. The caller holds +// m.mu. +func (m *Memory) deleteConnections(tenantID string) { + m.connInvites = slices.DeleteFunc(m.connInvites, func(i ConnectionInvite) bool { return i.TenantID == tenantID }) + for i := range m.connections { + c := &m.connections[i] + if c.TenantA == tenantID { + c.TenantA = "" + } + if c.TenantB == tenantID { + c.TenantB = "" + } + } +} diff --git a/internal/store/postgres.go b/internal/store/postgres.go index 9bb7c93..343d326 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -128,7 +128,12 @@ func (p *Postgres) CreateTenant(ctx context.Context, in TenantCreate) (*Tenant, } func (p *Postgres) GetTenant(ctx context.Context, id string) (*Tenant, error) { - return scanTenant(p.pool.QueryRow(ctx, tenantSelect+`WHERE id = $1::uuid`, id)) + t, err := scanTenant(p.pool.QueryRow(ctx, tenantSelect+`WHERE id = $1::uuid`, id)) + if isInvalidUUID(err) { + // Not a tenant id at all: unknown, as in the memory store. + return nil, ErrNotFound + } + return t, err } func (p *Postgres) GetTenantBySlug(ctx context.Context, slug string) (*Tenant, error) { diff --git a/internal/store/postgres_connections.go b/internal/store/postgres_connections.go new file mode 100644 index 0000000..a370efa --- /dev/null +++ b/internal/store/postgres_connections.go @@ -0,0 +1,245 @@ +package store + +import ( + "context" + "errors" + "time" + + "github.com/jackc/pgx/v5" +) + +// connectionSelect reads a connection with the current names of the sides +// that exist (the snapshot otherwise) and whether it is active: not ended, +// both tenants there and neither archived. +const connectionSelect = ` +SELECT c.id::text, COALESCE(c.tenant_a::text, ''), COALESCE(c.tenant_b::text, ''), + COALESCE(ta.name, c.name_a), COALESCE(tb.name, c.name_b), + c.created_at, c.ended_at, COALESCE(c.ended_by::text, ''), + (c.ended_at IS NULL AND ta.status IS NOT NULL AND tb.status IS NOT NULL + AND ta.status <> 'archived' AND tb.status <> 'archived') +FROM tenant_connections c +LEFT JOIN tenants ta ON ta.id = c.tenant_a +LEFT JOIN tenants tb ON tb.id = c.tenant_b ` + +type rowQuerier interface { + QueryRow(context.Context, string, ...any) pgx.Row +} + +func scanConnection(row pgx.Row) (*Connection, error) { + var c Connection + if err := row.Scan(&c.ID, &c.TenantA, &c.TenantB, &c.NameA, &c.NameB, &c.CreatedAt, &c.EndedAt, &c.EndedBy, &c.Active); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + c.CreatedAt = c.CreatedAt.UTC() + if c.EndedAt != nil { + t := c.EndedAt.UTC() + c.EndedAt = &t + } + return &c, nil +} + +func getConnection(ctx context.Context, q rowQuerier, id string) (*Connection, error) { + c, err := scanConnection(q.QueryRow(ctx, connectionSelect+`WHERE c.id = $1::uuid`, id)) + if isInvalidUUID(err) { + return nil, ErrNotFound + } + return c, err +} + +func (p *Postgres) CreateConnectionInvite(ctx context.Context, inv ConnectionInvite) (*ConnectionInvite, error) { + if !inv.valid() { + return nil, ErrInvalidInput + } + out := inv + out.UsedAt = nil + err := p.pool.QueryRow(ctx, ` + INSERT INTO connection_invites (tenant_id, code_hash, created_by, expires_at) + VALUES ($1::uuid, $2, $3, $4) + RETURNING id::text, created_at`, + inv.TenantID, inv.CodeHash, inv.CreatedBy, inv.ExpiresAt.UTC()).Scan(&out.ID, &out.CreatedAt) + switch { + case err == nil: + out.CreatedAt = out.CreatedAt.UTC() + out.ExpiresAt = out.ExpiresAt.UTC() + return &out, nil + case isFKViolation(err), isInvalidUUID(err): + return nil, ErrNotFound + case isUniqueViolation(err): + return nil, ErrConflict + case isCheckViolation(err): + return nil, ErrInvalidInput + } + return nil, err +} + +func (p *Postgres) ListConnectionInvites(ctx context.Context, tenantID string, now time.Time) ([]ConnectionInvite, error) { + rows, err := p.pool.Query(ctx, ` + SELECT id::text, tenant_id::text, created_by, created_at, expires_at + FROM connection_invites + WHERE tenant_id = $1::uuid AND used_at IS NULL AND expires_at > $2 + ORDER BY created_at, id`, tenantID, now.UTC()) + if isInvalidUUID(err) { + return []ConnectionInvite{}, nil + } + if err != nil { + return nil, err + } + defer rows.Close() + out := []ConnectionInvite{} + for rows.Next() { + var i ConnectionInvite + if err := rows.Scan(&i.ID, &i.TenantID, &i.CreatedBy, &i.CreatedAt, &i.ExpiresAt); err != nil { + return nil, err + } + i.CreatedAt, i.ExpiresAt = i.CreatedAt.UTC(), i.ExpiresAt.UTC() + out = append(out, i) + } + if err := rows.Err(); isInvalidUUID(err) { + return []ConnectionInvite{}, nil + } else if err != nil { + return nil, err + } + return out, nil +} + +func (p *Postgres) DeleteConnectionInvite(ctx context.Context, tenantID, id string) error { + tag, err := p.pool.Exec(ctx, ` + DELETE FROM connection_invites WHERE tenant_id = $1::uuid AND id = $2::uuid AND used_at IS NULL`, tenantID, id) + switch { + case isInvalidUUID(err): + return ErrNotFound + case err != nil: + return err + case tag.RowsAffected() == 0: + return ErrNotFound + } + return nil +} + +func (p *Postgres) RedeemConnectionInvite(ctx context.Context, codeHash []byte, tenantID string, now time.Time) (*Connection, error) { + tx, err := p.pool.Begin(ctx) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback(ctx) }() + // The row lock makes a second redeemer of the same code wait, then see + // it used. + var inviteID, issuer, issuerName, redeemerName string + err = tx.QueryRow(ctx, ` + SELECT i.id::text, ta.id::text, ta.name, tb.name + FROM connection_invites i + JOIN tenants ta ON ta.id = i.tenant_id + JOIN tenants tb ON tb.id = $2::uuid + WHERE i.code_hash = $1 AND i.used_at IS NULL AND i.expires_at > $3 + AND ta.id <> tb.id AND ta.status <> 'archived' AND tb.status <> 'archived' + FOR UPDATE OF i`, codeHash, tenantID, now.UTC()).Scan(&inviteID, &issuer, &issuerName, &redeemerName) + if errors.Is(err, pgx.ErrNoRows) || isInvalidUUID(err) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + var id string + err = tx.QueryRow(ctx, ` + INSERT INTO tenant_connections (tenant_a, tenant_b, name_a, name_b, created_at) + VALUES ($1::uuid, $2::uuid, $3, $4, $5) + RETURNING id::text`, issuer, tenantID, issuerName, redeemerName, now.UTC()).Scan(&id) + if isUniqueViolation(err) { + return nil, ErrConflict + } + if err != nil { + return nil, err + } + if _, err := tx.Exec(ctx, `UPDATE connection_invites SET used_at = $2 WHERE id = $1::uuid`, inviteID, now.UTC()); err != nil { + return nil, err + } + c, err := getConnection(ctx, tx, id) + if err != nil { + return nil, err + } + if err := tx.Commit(ctx); err != nil { + return nil, err + } + return c, nil +} + +func (p *Postgres) ListConnections(ctx context.Context, tenantID string) ([]Connection, error) { + rows, err := p.pool.Query(ctx, connectionSelect+` + WHERE c.tenant_a = $1::uuid OR c.tenant_b = $1::uuid + ORDER BY c.created_at DESC, c.id DESC`, tenantID) + if isInvalidUUID(err) { + return []Connection{}, nil + } + if err != nil { + return nil, err + } + defer rows.Close() + out := []Connection{} + for rows.Next() { + c, err := scanConnection(rows) + if err != nil { + return nil, err + } + out = append(out, *c) + } + if err := rows.Err(); isInvalidUUID(err) { + return []Connection{}, nil + } else if err != nil { + return nil, err + } + return out, nil +} + +func (p *Postgres) GetConnection(ctx context.Context, id string) (*Connection, error) { + return getConnection(ctx, p.pool, id) +} + +func (p *Postgres) EndConnection(ctx context.Context, tenantID, id string, at time.Time) (*Connection, bool, error) { + tag, err := p.pool.Exec(ctx, ` + UPDATE tenant_connections SET ended_at = $3, ended_by = $1::uuid + WHERE id = $2::uuid AND ended_at IS NULL AND (tenant_a = $1::uuid OR tenant_b = $1::uuid)`, + tenantID, id, at.UTC()) + if isInvalidUUID(err) { + return nil, false, ErrNotFound + } + if err != nil { + return nil, false, err + } + c, err := getConnection(ctx, p.pool, id) + if err != nil { + return nil, false, err + } + if c.TenantA != tenantID && c.TenantB != tenantID { + return nil, false, ErrNotFound + } + return c, tag.RowsAffected() > 0, nil +} + +func (p *Postgres) EndTenantConnections(ctx context.Context, tenantID string, at time.Time) ([]Connection, error) { + rows, err := p.pool.Query(ctx, ` + UPDATE tenant_connections SET ended_at = $2 + WHERE ended_at IS NULL AND (tenant_a = $1::uuid OR tenant_b = $1::uuid) + RETURNING id::text`, tenantID, at.UTC()) + if isInvalidUUID(err) { + return []Connection{}, nil + } + if err != nil { + return nil, err + } + ids, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + return nil, err + } + out := make([]Connection, 0, len(ids)) + for _, id := range ids { + c, err := getConnection(ctx, p.pool, id) + if err != nil { + return nil, err + } + out = append(out, *c) + } + return out, nil +} diff --git a/internal/store/store.go b/internal/store/store.go index 087fb4d..6b9c812 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -289,6 +289,34 @@ type Store interface { DeleteCapabilityRequest(ctx context.Context, tenantID, id string) error DeleteMemberCapabilityRequests(ctx context.Context, tenantID, userID, capability string) (int, error) + // Connections between tenants (0032, #138). + // + // CreateConnectionInvite stores a code (ErrNotFound for an unknown + // tenant, ErrInvalidInput for a malformed row). ListConnectionInvites + // lists a tenant's open codes (unused, not expired at now), oldest + // first. DeleteConnectionInvite withdraws an unused code; ErrNotFound + // otherwise. + // + // RedeemConnectionInvite connects tenantID to the tenant whose code + // hashes to codeHash, and uses the code up. ErrNotFound for every code + // that does not work: unknown, used, expired, the tenant's own, or + // either tenant archived or unknown. ErrConflict when the two are + // connected already; the code then stays unused. + // + // ListConnections lists a tenant's connections, newest first. + // GetConnection is ErrNotFound for an unknown id. EndConnection ends an + // open connection of tenantID (ended=false when it had ended already; + // ErrNotFound when tenantID is not a side). EndTenantConnections ends + // every open connection of a tenant, by the registry, and returns them. + CreateConnectionInvite(ctx context.Context, inv ConnectionInvite) (*ConnectionInvite, error) + ListConnectionInvites(ctx context.Context, tenantID string, now time.Time) ([]ConnectionInvite, error) + DeleteConnectionInvite(ctx context.Context, tenantID, id string) error + RedeemConnectionInvite(ctx context.Context, codeHash []byte, tenantID string, now time.Time) (*Connection, error) + ListConnections(ctx context.Context, tenantID string) ([]Connection, error) + GetConnection(ctx context.Context, id string) (*Connection, error) + EndConnection(ctx context.Context, tenantID, id string, at time.Time) (conn *Connection, ended bool, err error) + EndTenantConnections(ctx context.Context, tenantID string, at time.Time) ([]Connection, error) + // Product settings (0025): the workspace's own choices per product, // untouched by the ERP recompute. GetTenantProductSettings is // ErrNotFound when none were saved; PutTenantProductSettings replaces diff --git a/migrations/0032_tenant_connections.down.sql b/migrations/0032_tenant_connections.down.sql new file mode 100644 index 0000000..2cf2c8c --- /dev/null +++ b/migrations/0032_tenant_connections.down.sql @@ -0,0 +1,2 @@ +DROP TABLE IF EXISTS tenant_connections; +DROP TABLE IF EXISTS connection_invites; diff --git a/migrations/0032_tenant_connections.up.sql b/migrations/0032_tenant_connections.up.sql new file mode 100644 index 0000000..bda0c19 --- /dev/null +++ b/migrations/0032_tenant_connections.up.sql @@ -0,0 +1,41 @@ +-- Connections between tenants (#138): one tenant creates a code, another +-- redeems it, and the two are connected. Products (Prüfwerk's supplier SBOM +-- releases first) send data over a connection; the registry only knows who +-- is connected to whom. +-- +-- A code is stored as its SHA-256 only. It works once and until expires_at; +-- the row stays after use (used_at) so the code can never work again, and +-- is deleted when withdrawn or when its tenant goes. +CREATE TABLE connection_invites ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + code_hash BYTEA NOT NULL UNIQUE CHECK (octet_length(code_hash) = 32), + created_by TEXT NOT NULL DEFAULT '' CHECK (char_length(created_by) <= 320), + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ NOT NULL, + used_at TIMESTAMPTZ +); +CREATE INDEX connection_invites_tenant ON connection_invites (tenant_id); + +-- tenant_a created the code, tenant_b redeemed it. A purged tenant's side +-- turns NULL, so the other side keeps the (ended) connection in its list; +-- name_a and name_b are the display names at connection time, shown for a +-- side that no longer exists. ended_by is the side that ended it, NULL when +-- the registry did (a tenant archived). +CREATE TABLE tenant_connections ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + tenant_a UUID REFERENCES tenants(id) ON DELETE SET NULL, + tenant_b UUID REFERENCES tenants(id) ON DELETE SET NULL, + name_a TEXT NOT NULL, + name_b TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + ended_at TIMESTAMPTZ, + ended_by UUID, + CHECK (tenant_a IS DISTINCT FROM tenant_b OR tenant_a IS NULL) +); +CREATE INDEX tenant_connections_a ON tenant_connections (tenant_a); +CREATE INDEX tenant_connections_b ON tenant_connections (tenant_b); +-- Two tenants have at most one connection that has not ended. +CREATE UNIQUE INDEX tenant_connections_open_pair + ON tenant_connections (LEAST(tenant_a, tenant_b), GREATEST(tenant_a, tenant_b)) + WHERE ended_at IS NULL; diff --git a/openapi.yaml b/openapi.yaml index 4a26ba0..fb804a3 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -1140,6 +1140,184 @@ paths: "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/connection-invites: + post: + summary: Create a code another workspace enters to connect (#138). + description: | + The code (160 random bits, shown as eight groups of four) is in this + answer only; the registry keeps its SHA-256. It works once, for 14 + days. 409 `too_many_invites` with 20 open codes. User tokens need + IT_ADMIN or OWNER in their own tenant; service clients `tenants.write`. + Audit: `connection.invite_created`. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "201": + description: The new code. + content: + application/json: { schema: { $ref: "#/components/schemas/ConnectionInvite" } } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + "409": { $ref: "#/components/responses/Conflict" } + get: + summary: The workspace's open codes, oldest first, without the codes. + description: | + Same caller rules as the POST, with `tenants.read` for service clients. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The open codes. + content: + application/json: + schema: + type: object + required: [items] + properties: + items: + type: array + items: { $ref: "#/components/schemas/ConnectionInvite" } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/tenants/{id}/connection-invites/{invite}: + delete: + summary: Withdraw an unused code. + description: | + Same caller rules as creating one. Audit: `connection.invite_withdrawn`. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: invite, required: true, schema: { type: string, format: uuid } } + responses: + "204": { description: Withdrawn. } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/tenants/{id}/connections: + post: + summary: Enter another workspace's code; the two are connected at once. + description: | + Every code that does not work (unknown, used, expired, withdrawn, the + workspace's own, or a workspace archived) gets the same 404 + `invalid_code`. 409 `already_connected`; the code then stays open. + 429 `rate_limited` after 20 codes per hour from the workspace or the + person. Same caller rules as creating a code. Audit: + `connection.created` in both workspaces' logs; the other side's entry + names neither the person nor the address. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [code] + properties: + code: { type: string, description: "Case, spaces and dashes do not matter." } + responses: + "201": + description: Connected. + content: + application/json: { schema: { $ref: "#/components/schemas/Connection" } } + "400": { $ref: "#/components/responses/BadRequest" } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + "409": { $ref: "#/components/responses/Conflict" } + "429": { description: "Too many codes entered in the last hour." } + get: + summary: The workspace's connections, newest first. + description: | + Each shows only the other workspace's display name. Same caller rules + as the POST, with `tenants.read` for service clients. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The connections. + content: + application/json: + schema: + type: object + required: [items] + properties: + items: + type: array + items: { $ref: "#/components/schemas/Connection" } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/tenants/{id}/connections/{connection}/end: + post: + summary: End a connection; either side may. + description: | + Ending one that has ended answers it unchanged. Same caller rules as + entering a code. Audit: `connection.ended` in both logs. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: connection, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: Ended. + content: + application/json: { schema: { $ref: "#/components/schemas/Connection" } } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/internal/tenants/{id}/connections: + get: + summary: A tenant's active connections, for a product to deliver over. + description: | + Route group `connections.read`. Active: not ended, and neither + workspace archived. The peer's tenant id is for the product's own + delivery; it is never shown to anyone. 404 for an unknown tenant. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: query, name: state, required: false, schema: { type: string, enum: [active] } } + responses: + "200": + description: The active connections. + content: + application/json: + schema: + type: object + required: [items] + properties: + items: + type: array + items: + type: object + required: [id, peer_tenant_id, peer_name] + properties: + id: { type: string, format: uuid } + peer_tenant_id: { type: string, format: uuid } + peer_name: { type: string } + "400": { $ref: "#/components/responses/BadRequest" } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/internal/connections/{connection}: + get: + summary: Whether a connection is active, and the tenants it joins. + description: | + Route group `connections.read`. A product asks it before every + delivery. `tenant_ids` lists the sides that still exist. + parameters: + - { in: path, name: connection, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The connection. + content: + application/json: + schema: + type: object + required: [active, tenant_ids] + properties: + active: { type: boolean } + tenant_ids: + type: array + items: { type: string, format: uuid } + "404": { $ref: "#/components/responses/NotFound" } + /v1/admin/tenants: get: summary: Staff tenant list with search and 30-day activity. @@ -3135,6 +3313,25 @@ components: description: The member's active API keys in this tenant, offered for revocation. items: { $ref: "#/components/schemas/APIKey" } + ConnectionInvite: + type: object + required: [id, created_at, expires_at] + properties: + id: { type: string, format: uuid } + code: { type: string, description: "Only in the answer that created it." } + created_by: { type: string } + created_at: { type: string, format: date-time } + expires_at: { type: string, format: date-time } + Connection: + type: object + required: [id, peer_name, state, created_at, ended_by_us] + properties: + id: { type: string, format: uuid } + peer_name: { type: string, description: "The other workspace's display name." } + state: { type: string, enum: [active, ended] } + created_at: { type: string, format: date-time } + ended_at: { type: string, format: date-time } + ended_by_us: { type: boolean, description: "False also when the registry ended it (a workspace archived)." } CapabilityRequest: type: object required: [id, tenant_id, user_id, capability, requested_by, created_at] -- 2.54.1 From 3ef530b504d0641002bd2ad6daee8a8118868037 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:43:35 +0100 Subject: [PATCH 2/2] fix(connections): refuse user tokens on product routes The two internal routes carry the peer's tenant id, which no person sees; a user token is now refused there whatever groups its client holds. The per-person window for entering codes applies only when a person is named: keyed on the portal's own client, one workspace's attempts would have blocked every other workspace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 --- internal/server/connections.go | 29 +++++++++++-- internal/server/connections_scope_test.go | 52 +++++++++++++++++++++++ internal/server/connections_test.go | 10 ++--- 3 files changed, 82 insertions(+), 9 deletions(-) diff --git a/internal/server/connections.go b/internal/server/connections.go index 0a87da4..7c81a03 100644 --- a/internal/server/connections.go +++ b/internal/server/connections.go @@ -246,10 +246,14 @@ func (s *Server) redeemConnectionInvite(w http.ResponseWriter, r *http.Request) actor := s.teamActor(r) now := s.now() // Both windows count every attempt, so neither a tenant nor one person - // can try codes faster than the rate. - tenantOK := s.connLimiter.allow("tenant:"+t.ID, now, connectionRedeemRate) - personOK := s.connLimiter.allow("person:"+firstNonEmpty(actor.ID, actor.Email, actor.Type), now, connectionRedeemRate) - if !tenantOK || !personOK { + // can try codes faster than the rate. A call that names no person (a + // service client without X-Portal-User-*) has the tenant window only: + // keyed on the client, one workspace's attempts would block every other. + allowed := s.connLimiter.allow("tenant:"+t.ID, now, connectionRedeemRate) + if person := firstNonEmpty(actor.ID, actor.Email); actor.Type != "service" && person != "" { + allowed = s.connLimiter.allow("person:"+person, now, connectionRedeemRate) && allowed + } + if !allowed { w.Header().Set("Retry-After", "3600") writeError(w, http.StatusTooManyRequests, "rate_limited", "too many codes entered; try again later") return @@ -371,10 +375,24 @@ type productConnection struct { PeerName string `json:"peer_name"` } +// productOnly refuses a user token on the product routes: they carry the +// peer's tenant id, which no person ever sees, whatever groups the token's +// client holds. +func productOnly(w http.ResponseWriter, r *http.Request) bool { + if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() { + writeError(w, http.StatusForbidden, "FORBIDDEN_CLIENT", "products only") + return false + } + return true +} + // internalTenantConnections is GET /v1/internal/tenants/{id}/connections // ?state=active: the tenant's active connections with the peer's tenant id, // for a product to deliver over. 404 for an unknown tenant. func (s *Server) internalTenantConnections(w http.ResponseWriter, r *http.Request) { + if !productOnly(w, r) { + return + } if st := r.URL.Query().Get("state"); st != "" && st != "active" { writeError(w, http.StatusBadRequest, "invalid_state", "state must be active") return @@ -409,6 +427,9 @@ func (s *Server) internalTenantConnections(w http.ResponseWriter, r *http.Reques // it is active and the tenants it joins. A product asks it before every // delivery. 404 for an unknown id. func (s *Server) checkConnection(w http.ResponseWriter, r *http.Request) { + if !productOnly(w, r) { + return + } ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) defer cancel() c, err := s.Store.GetConnection(ctx, r.PathValue("connection")) diff --git a/internal/server/connections_scope_test.go b/internal/server/connections_scope_test.go index 30b8a31..4be9b40 100644 --- a/internal/server/connections_scope_test.go +++ b/internal/server/connections_scope_test.go @@ -7,6 +7,7 @@ import ( "testing" "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/store" ) // Only a workspace administrator may create, enter or end, and only in its @@ -52,3 +53,54 @@ func TestConnections_userRoles(t *testing.T) { } } } + +// The product routes refuse a person's token, whatever its client holds; +// they carry the peer's tenant id. +func TestConnections_productRoutesRefuseUsers(t *testing.T) { + p := &authn.Principal{Subject: "u-1", ClientID: "portal", TenantID: "00000000-0000-0000-0000-000000000001", OrgRoles: []string{"IT_ADMIN"}} + _, h, tenant := scopedServer(t, p, "portal:*") + for _, path := range []string{ + "/v1/internal/tenants/" + tenant.ID + "/connections?state=active", + "/v1/internal/connections/00000000-0000-0000-0000-000000000002", + } { + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, path, nil)) + if rr.Code != http.StatusForbidden { + t.Errorf("%s: %d %s", path, rr.Code, rr.Body.String()) + } + } +} + +// The person window follows the person the portal names, across +// workspaces; the portal's own client is never a person. +func TestConnections_personWindow(t *testing.T) { + portal := &authn.Principal{Subject: "svc-portal", ClientID: "portal-svc"} + s, h, acme := scopedServer(t, portal, "portal-svc:tenants,users.act") + other, err := s.Store.CreateTenant(t.Context(), store.TenantCreate{Slug: "beta", Name: "Beta GmbH", Plan: "professional"}) + if err != nil { + t.Fatal(err) + } + redeem := func(tenantID, subject string) int { + req := httptest.NewRequest(http.MethodPost, "/v1/tenants/"+tenantID+"/connections", strings.NewReader(`{"code":"x"}`)) + if subject != "" { + req.Header.Set(headerPortalUserSubject, subject) + } + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + return rr.Code + } + for i := 0; i < connectionRedeemRate; i++ { + if got := redeem(acme.ID, "u-7"); got != http.StatusNotFound { + t.Fatalf("attempt %d: %d", i, got) + } + } + if got := redeem(other.ID, "u-7"); got != http.StatusTooManyRequests { + t.Fatalf("the same person in another workspace: %d", got) + } + if got := redeem(other.ID, "u-8"); got != http.StatusNotFound { + t.Fatalf("another person there: %d", got) + } + if got := redeem(other.ID, ""); got != http.StatusNotFound { + t.Fatalf("the portal naming nobody: %d", got) + } +} diff --git a/internal/server/connections_test.go b/internal/server/connections_test.go index a10f7f2..d509ace 100644 --- a/internal/server/connections_test.go +++ b/internal/server/connections_test.go @@ -347,7 +347,7 @@ func TestConnections_productRoutes(t *testing.T) { }) } -// Entering codes is limited per tenant, working or not. +// Entering codes is limited per workspace, working or not. func TestConnections_redeemRateLimit(t *testing.T) { h := newMemoryHarness(t) defer h.Close() @@ -360,11 +360,11 @@ func TestConnections_redeemRateLimit(t *testing.T) { if status, raw := h.redeem(b.ID, "AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA-AAAA"); status != http.StatusTooManyRequests { t.Fatalf("21st attempt: %d %s", status, raw) } - // Another tenant has its own window, but the same caller does not: - // without a principal every request is the same caller here. + // Another tenant has its own window; a call naming no person has no + // person window, so one workspace's attempts never block another's. c, _ := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "gamma", Name: "Gamma AG", Plan: "professional"}) - if status, _ := h.redeem(c.ID, "x"); status != http.StatusTooManyRequests { - t.Fatalf("per caller: %d", status) + if status, raw := h.redeem(c.ID, "x"); status != http.StatusNotFound { + t.Fatalf("another workspace: %d %s", status, raw) } } -- 2.54.1