Files
tenant-registry/internal/server/connections.go
T
sharangandSharang Parnerkar c6de35858e
ci / shared (push) Successful in 12s
ci / test (push) Successful in 6m30s
ci / image (push) Successful in 38s
feat(connections): connect two workspaces by code (#138) (#145)
## What

- **Codes:** two workspaces connect by code. One administrator creates a code; another workspace's administrator enters it, and the two are connected at once. Each side sees only the other's display name.
- **Ending:** either side can end a connection. Archiving a workspace ends all of its connections. When a workspace is purged, the other side keeps the ended connection under the name it knew.
- **Product routes:** products (Prüfwerk's supplier SBOM releases first) list a tenant's active connections and check one before each delivery, under a new route group `connections.read`.

## Why

Closes #138. This is phase 4 of platform/pruefwerk#1028. Prüfwerk's agent is on stage and already calls the two internal routes; without them the release screen warns that connections can't be read (see the comment on #138).

Linked milestone: **n/a** (Prüfwerk #1028, phase 4)

## How

**Routes:**

| Call | Group | Answer |
|---|---|---|
| `POST /v1/tenants/{id}/connection-invites` | tenants.write | `201 {id, code, created_at, expires_at}`; the code is in this answer only |
| `GET /v1/tenants/{id}/connection-invites` | tenants.read | open codes, without the codes |
| `DELETE /v1/tenants/{id}/connection-invites/{invite}` | tenants.write | `204`, withdraws an unused code |
| `POST /v1/tenants/{id}/connections` `{code}` | tenants.write | `201 {id, peer_name, state, created_at, ended_by_us}` |
| `GET /v1/tenants/{id}/connections` | tenants.read | `{items: [...]}`, newest first |
| `POST /v1/tenants/{id}/connections/{connection}/end` | tenants.write | `200`; ending one that has ended answers it unchanged |
| `GET /v1/internal/tenants/{id}/connections?state=active` | **connections.read** | `{items: [{id, peer_tenant_id, peer_name}]}`; 404 for an unknown tenant |
| `GET /v1/internal/connections/{connection}` | **connections.read** | `{active, tenant_ids}`; 404 for an unknown id |

The two internal answers match what `compliance-agent/src/registry.rs` reads. A test pins the `items` key, because the agent defaults a missing key to "no connections".

**Codes:**
- 160 random bits (`crypto/rand`), shown as eight groups of four base32 letters.
- Stored as SHA-256 only, looked up by hash; case, spaces and dashes don't matter.
- Valid for 14 days, single use, at most 20 open per workspace.
- Every code that doesn't work gets the same 404 `invalid_code`: unknown, used, expired, withdrawn, the workspace's own, or either workspace archived.
- 409 `already_connected` when the two are connected already; the code then stays open.
- Entering codes is limited to 20 per hour per workspace, and per person when the call names one (`keyRateLimiter` now takes its limit as an argument; CI licences keep theirs). A call from the portal's own client that names nobody has only the workspace limit. Otherwise every workspace would share one limit through that client. **portal#201 must send `X-Portal-User-Subject`.**

**Redeeming** is one transaction. `SELECT … FOR UPDATE` on the code, insert the connection, then mark the code used. A partial unique index allows at most one connection per pair of workspaces that hasn't ended. A race test has two workspaces enter one code at the same time: exactly one connects.

**Active** is derived on every read: not ended, both workspaces exist, and neither is archived. So no delivery can go to an archived workspace, even if writing the end failed.

**Ending on archive:** every status change passes through `syncTenantStatus`, which now ends an archived workspace's connections. The admin purge calls the same step again before `DeleteTenant`, as a safety net. The foreign keys are `ON DELETE SET NULL`, with name snapshots, so the other side keeps its history.

**Audit:** `connection.invite_created`, `connection.invite_withdrawn`, `connection.created` and `connection.ended` go into both workspaces' logs.
- The acting side's entry names the actor.
- The other side's entry is a system entry with `by: peer`: no person, IP or user agent, only the connection id and the acting side's display name.
- Ends caused by archiving carry `reason: tenant_archived`.

**Product routes refuse user tokens** (403 `FORBIDDEN_CLIENT`), whatever groups the token's client holds, because they carry the peer's tenant id.

**Who may:** user tokens need IT_ADMIN or OWNER in their own workspace (the existing team gate, `IsTenantAdmin`). Another workspace's administrator gets a 404. The portal calls as its service client, naming the person in `X-Portal-User-*`.

**Side fix:** the Postgres `GetTenant` now answers a non-UUID id as not found (404), as the memory store does. It was a 500, which the new internal route hit.

## Test plan

- [x] Unit tests: route groups in `authz_test`, roles and cross-tenant scoping in `connections_scope_test`, and the OpenAPI contract cases.
- [x] Integration tests on memory **and Postgres (testcontainers)** in `connections_test.go`, run locally:
  - connect, list, product view, check, and the re-connect after end;
  - every invalid code gives the same answer, including expiry with an injected clock;
  - archive, then purge;
  - unknown ids;
  - the rate limit;
  - the redeem race.
- [x] The whole `internal/server` suite runs against Postgres locally (`go test -count=1 ./internal/server/`, 236 s, green). `-race` is green on the connection tests. `go vet` and `golangci-lint` v2.12.2: 0 issues.
- [ ] Playwright e2e: n/a, there's no UI here (portal#201).
- [ ] Manual smoke on stage after deploy, once `AUTHZ_RULES` carries the grant below. Prüfwerk's release screen should then show no warning.

## Risk

**Blast radius:** new tables and routes only. Existing routes change in two small ways: the `GetTenant` 500→404 for non-UUID ids, and the archive path now also ends connections.

**What could break:**
- **Migration number:** `0032` is also used by the open onprem PRs (#142/#143, `0032_werkpilot_description`). Whichever merges second must renumber. A duplicate version fails the migrations test loudly. I didn't pick 0033, because golang-migrate would silently skip a 0032 that merges after it.
- **Deployment grant:** the new group needs a grant in stage and prod `AUTHZ_RULES`. That config isn't in this repo: `pruefwerk-svc-stage:…,connections.read`, and the same for prod. Until it's added, Prüfwerk keeps getting 403.

**Rollback plan:** revert the PR and redeploy. The down migration drops both tables.

## Decided (2026-11-20, by the product owner)

- **Archived only** ends connections. A `halted` workspace keeps them, so a returning customer finds them again. Active stays false while a side is archived.
- **IT_ADMIN or OWNER** may create, enter and end, using the existing team gate rather than a new catalogue right.

## Open points for review

1. **Retention:** a purged workspace's display name stays visible to its former peers through the name snapshot, with no time limit. Should it be dropped after a while?
2. **Additions to the sketch:** the create answer now carries the invite `id`, which the withdraw route needs, and there's a list of open codes, without the codes.

## Checklist

- [x] Docs updated: the OpenAPI spec and the package doc in `connections.go` (no separate docs page for registry routes)
- [x] Audit events emitted for state changes
- [x] Secrets via Infisical, never in repo (none involved)
- [x] Migration is forward-only (new tables; down drops them)
- [x] Tenant scoping enforced on every DB query
- [x] OpenAPI spec updated
- [ ] `featureFlags.evaluate()`: n/a (nothing toggleable)
- [ ] CHANGELOG entry: n/a (generated by git-cliff on release)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #145
2026-11-20 08:54:44 +00:00

445 lines
16 KiB
Go

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()})
}