Files
tenant-registry/internal/server/connections_test.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

396 lines
14 KiB
Go

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 workspace, 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; 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, raw := h.redeem(c.ID, "x"); status != http.StatusNotFound {
t.Fatalf("another workspace: %d %s", status, raw)
}
}
// 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)
}
})
}