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

233 lines
8.1 KiB
Go

package server
import (
"context"
"errors"
"net/http"
"net/mail"
"strings"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"git.breakpilot.com/platform/tenant-registry/internal/authz"
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// Tenant members (D1): the portal's Settings/Users page reads the Keycloak
// organization membership through the registry and invites new users the
// same way the first admin was invited at tenant creation.
//
// Scope: a user token (tenant context) may only touch its own tenant — a
// mismatch is a 404 like revokeLicence, never a hint that the tenant
// exists. Service clients are gated per route group by AUTHZ_RULES
// (members = tenants.read, invites = tenants.write).
// defaultInviteRole is written when the invite carries no role. The first
// admin gets IT_ADMIN from CreateOrgAndInvite; everyone else is a USER
// unless the portal says otherwise.
const defaultInviteRole = "USER"
type membersResp struct {
Members []keycloak.OrgMember `json:"members"`
}
type inviteReq struct {
Email string `json:"email"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
Role string `json:"role,omitempty"`
}
type inviteResp struct {
UserID string `json:"user_id"`
Email string `json:"email"`
Status string `json:"status"` // invited | member
}
// tenantInScope loads the tenant and enforces the user-token scope. On a
// miss or a cross-tenant user the response is already written (404).
func (s *Server) tenantInScope(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, bool) {
t, err := s.Store.GetTenant(ctx, r.PathValue("id"))
if err != nil {
if mapStoreError(w, err) {
return nil, false
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return nil, false
}
if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && p.TenantID != t.ID {
writeError(w, http.StatusNotFound, "not_found", "resource does not exist")
return nil, false
}
return t, true
}
// listTenantMembers is GET /v1/tenants/{id}/members.
// tenantSubresources are the collections tenantSubresource serves (keep the
// two in step). A request's route name (span, access log) carries the one it
// asked for, never any other path segment.
var tenantSubresources = []string{
"members", "documents", "projects", "contracts",
"managed-services", "company-profile", "role-dataset", "store",
"module-users", "connections", "connection-invites",
}
// tenantSubresource dispatches GET /v1/tenants/{id}/{sub}. Only the members
// collection exists; anything else is a 404 rather than a route that silently
// swallowed a typo.
func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) {
switch r.PathValue("sub") {
case "members":
s.listTenantMembers(w, r)
case "documents":
s.listTenantDocuments(w, r)
case "projects":
s.listTenantProjects(w, r)
case "contracts":
s.listTenantContracts(w, r)
case "managed-services":
s.listTenantManagedServices(w, r)
case "company-profile":
s.getCompanyProfile(w, r)
case "role-dataset":
s.getRoleDataset(w, r)
case "store":
s.listStore(w, r)
case "capability-requests":
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")
}
}
func (s *Server) listTenantMembers(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
members, err := s.Keycloak.ListOrgMembers(ctx, t.Slug)
if err != nil {
if errors.Is(err, keycloak.ErrOrgNotFound) {
// Nobody was ever invited (sales-led tenant): an empty list, not
// an error — the portal renders "no users yet".
writeJSON(w, http.StatusOK, membersResp{Members: []keycloak.OrgMember{}})
return
}
s.writeKeycloakError(w, t.ID, "list members", err)
return
}
if members == nil {
members = []keycloak.OrgMember{}
}
decorateMembers(members, t.ID)
writeJSON(w, http.StatusOK, membersResp{Members: members})
}
// inviteTenantMember is POST /v1/tenants/{id}/invites. Tenant admins
// (org_roles IT_ADMIN/OWNER) and service clients on tenants.write only.
func (s *Server) inviteTenantMember(w http.ResponseWriter, r *http.Request) {
var in inviteReq
if !decodeJSON(w, r, &in) {
return
}
in.Email = strings.ToLower(strings.TrimSpace(in.Email))
if addr, err := mail.ParseAddress(in.Email); err != nil || addr.Address != in.Email || len(in.Email) > 254 {
writeError(w, http.StatusBadRequest, "invalid_email", "email must be a bare, valid address")
return
}
in.FirstName, in.LastName = strings.TrimSpace(in.FirstName), strings.TrimSpace(in.LastName)
if len(in.FirstName) > 100 || len(in.LastName) > 100 {
writeError(w, http.StatusBadRequest, "invalid_name", "first_name and last_name must be at most 100 chars")
return
}
in.Role = strings.ToUpper(strings.TrimSpace(in.Role))
if in.Role == "" {
in.Role = defaultInviteRole
}
// The role is a bundle of the rights catalogue a person may be given.
if !authz.IsAssignable(in.Role) {
writeError(w, http.StatusBadRequest, "invalid_role", "role must be one of "+strings.Join(authz.Assignable(), ", "))
return
}
p, _ := authn.PrincipalFrom(r.Context())
if p.IsUser() && !p.IsTenantAdmin() {
writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "inviting users requires the IT_ADMIN or OWNER org role")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
res, err := s.Keycloak.InviteMember(ctx, keycloak.MemberInviteInput{
TenantID: t.ID, Slug: t.Slug, TenantStatus: t.Status,
Email: in.Email, FirstName: in.FirstName, LastName: in.LastName, Role: in.Role,
})
if err != nil {
if errors.Is(err, keycloak.ErrOrgNotFound) {
writeError(w, http.StatusConflict, "org_not_provisioned", "tenant has no Keycloak organization yet — create it by inviting the first admin (POST /v1/tenants admin_email)")
return
}
s.writeKeycloakError(w, t.ID, "invite member", err)
return
}
if res.Status == keycloak.InviteStatusMember {
writeJSON(w, http.StatusOK, inviteResp{UserID: res.UserID, Email: in.Email, Status: res.Status})
return
}
meta := map[string]interface{}{"role": in.Role, "user_id": res.UserID, "user_created": res.Created}
if res.MailError != nil {
s.Log.Warn("invite mail failed", "tenant_id", t.ID, "user_id", res.UserID, "err", res.MailError)
meta["mail_error"] = res.MailError.Error()
}
ev := store.AuditEvent{
TenantID: t.ID, Action: "user.invited",
TargetID: in.Email, TargetType: "user", TargetName: in.Email,
Metadata: meta,
}
if p != nil {
ev.ActorID, ev.ActorName = p.Subject, p.Email
ev.ActorType = "service"
if p.IsUser() {
ev.ActorType = "user"
}
}
s.emitAudit(ctx, r, ev)
// The first admin invited into a tenant that was created without one
// (sales-led flow) becomes its admin_email.
if t.AdminEmail == "" && (in.Role == authn.RoleITAdmin || in.Role == authn.RoleOwner) {
if _, uerr := s.Store.UpdateTenant(ctx, t.ID, store.TenantUpdate{AdminEmail: ptrStr(in.Email)}); uerr != nil {
s.Log.Warn("admin_email not recorded", "tenant_id", t.ID, "err", uerr)
}
}
writeJSON(w, http.StatusAccepted, inviteResp{UserID: res.UserID, Email: in.Email, Status: res.Status})
}
// writeKeycloakError maps adapter failures: unreachable/unauthorized are a
// 503 (the portal shows "identity provider unavailable"), anything else 502.
func (s *Server) writeKeycloakError(w http.ResponseWriter, tenantID, op string, err error) {
s.Log.Error("keycloak "+op+" failed", "tenant_id", tenantID, "err", err)
if errors.Is(err, keycloak.ErrUnavailable) || errors.Is(err, keycloak.ErrUnauthorized) {
writeError(w, http.StatusServiceUnavailable, "keycloak_unavailable", err.Error())
return
}
writeError(w, http.StatusBadGateway, "keycloak_error", err.Error())
}