Files
tenant-registry/internal/server/members.go
T
Sharang ParnerkarandClaude Opus 5.5 da6eef6d30
ci / shared (pull_request) Successful in 13s
ci / test (pull_request) Successful in 23m11s
ci / image (pull_request) Skipped
feat(documents): tenant documents in object storage
Staff upload a file for a tenant as a draft (streamed to an S3 bucket,
hashed on the way, never buffered whole), publish it, or delete it;
the tenant lists its published documents and gets a five-minute
presigned download link. Uploads, publications and downloads are
audited, a download under the person the portal names.

Migration 0008 adds the documents table; internal/storage wraps
minio-go (Hetzner Object Storage, the bucket is created in its
region when missing). Without DOCUMENTS_S3_* the routes answer 503
and the rest of the registry is unaffected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-23 19:35:05 +02:00

207 lines
7.3 KiB
Go

package server
import (
"context"
"errors"
"net/http"
"net/mail"
"regexp"
"strings"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"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).
// roleRE bounds the org_roles value written for a new user. It is a
// Keycloak user attribute the portal projects into the token, not a role
// model the registry owns — any upper-snake identifier is accepted.
var roleRE = regexp.MustCompile(`^[A-Z][A-Z0-9_]{1,31}$`)
// 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.
// 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)
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{}
}
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
}
if !roleRE.MatchString(in.Role) {
writeError(w, http.StatusBadRequest, "invalid_role", "role must match ^[A-Z][A-Z0-9_]{1,31}$")
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())
}