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. 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 } 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"` } // 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 } 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) { 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")) 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()}) }