Files
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

246 lines
7.2 KiB
Go

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
}