The free trial follows the contract states of the epic: the customer's
binding offer (§ 2 Abs. 1 Testbedingungen) → receipt with confirmation link
(§ 312i Abs. 1 Nr. 3 BGB) → Breakpilot accepts by activating once the
address is confirmed: contract concluded, 14 calendar days start.
- Trial terms v1.0 ("Bedingungen für den kostenlosen Breakpilot-Testzugang",
Stand 1. Oktober 2026) as committed Markdown, HTML and PDF, embedded, with
pinned SHA-256; public at /v1/legal/trial-terms[/1.0.{pdf,html,md}], the
same bytes before the offer, in the activation mail and in the tenant's
Vertragsunterlagen.
- Migration 0011 trial_offers: the offer snapshot (company, address, person,
e-mail, terms id/version/sha256, 246c notice version, flow version,
language, offered_at) is immutable (trigger); only the state moves.
No IP address or browser fingerprint.
- POST /v1/trial-offers: validation, version check against what the portal
showed (409 version_mismatch), 409 email_taken, 429 within 10 minutes;
receipt mail with a single-use 72-hour link (only its hash is stored).
- POST /v1/trial-offers/verify: activated / already_activated / 410 expired
/ 404 invalid. Activation creates the tenant (slug from the company name),
the Keycloak account with the address already verified (only
UPDATE_PASSWORD), trial_ends_at = contract time + 14 calendar days in
Berlin time, the audit chain (offer_submitted, email_verified,
contract_accepted, activated) and the activation mail with the PDF.
- POST /v1/trial-offers/{id}/resend; GET /v1/tenants/{id}/contracts (trial,
AVV, TOMs, SaaS; trial null for tenants without an offer) and the exact
accepted PDF; trial.extension_granted event from the admin extension.
- mail: attachments (multipart/mixed); German-only registry mails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
211 lines
7.3 KiB
Go
211 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)
|
|
case "projects":
|
|
s.listTenantProjects(w, r)
|
|
case "contracts":
|
|
s.listTenantContracts(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())
|
|
}
|