From bab7475a6c451467ea3d05b99e81c1679f615b12 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 23 Sep 2026 19:23:00 +0200 Subject: [PATCH 1/2] feat(admin): staff tenant list, detail, trial extension, invite resend A new route group "admin" (the portal's service client only) serves the staff admin area: tenant search with 30-day usage and last activity, one detail call with entitlements, subscriptions, licences, members and recent audit, trial extension (moves trial entitlements with it and reopens a trial that expired into read-only), invite resend, and the audit log across tenants. Changes made from the admin area are audited under the staff member the portal names in X-Staff-Subject / X-Staff-Email; the header only counts from a client that holds the admin group. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- internal/keycloak/adapter.go | 5 + internal/keycloak/members.go | 15 ++ internal/keycloak/mock.go | 22 ++ internal/server/admin.go | 296 +++++++++++++++++++++++ internal/server/admin_test.go | 177 ++++++++++++++ internal/server/authz.go | 2 + internal/server/authz_middleware_test.go | 37 +++ internal/server/openapi_test.go | 5 + internal/server/server.go | 7 + internal/server/tenants.go | 4 + internal/store/memory.go | 44 ++++ internal/store/postgres.go | 67 +++++ internal/store/store.go | 3 + internal/store/types.go | 10 + openapi.yaml | 130 ++++++++++ 15 files changed, 824 insertions(+) create mode 100644 internal/server/admin.go create mode 100644 internal/server/admin_test.go diff --git a/internal/keycloak/adapter.go b/internal/keycloak/adapter.go index 51bc29c..4287e8a 100644 --- a/internal/keycloak/adapter.go +++ b/internal/keycloak/adapter.go @@ -141,6 +141,11 @@ type Adapter interface { // missing. InviteMember(ctx context.Context, in MemberInviteInput) (*MemberInviteResult, error) + // ResendInvite mails the invitation again to a member of the organization + // whose alias is slug (verify email + set password). ErrOrgNotFound when + // the org is missing, ErrUserNotFound when email is not a member of it. + ResendInvite(ctx context.Context, slug, email string) error + // SyncTenantStatus writes the coarse tenant_status attribute on every // member of the organization whose alias is slug (ERP/02: Keycloak // carries only the coarse flag; entitlements stay in the registry). diff --git a/internal/keycloak/members.go b/internal/keycloak/members.go index 73df540..d944160 100644 --- a/internal/keycloak/members.go +++ b/internal/keycloak/members.go @@ -8,6 +8,7 @@ import ( "log/slog" "net/http" "net/url" + "strings" "time" ) @@ -216,3 +217,17 @@ func (a *HTTPAdapter) ensureUserAttributes(ctx context.Context, userID string, a } return nil } + +func (a *HTTPAdapter) ResendInvite(ctx context.Context, slug, email string) error { + members, err := a.ListOrgMembers(ctx, slug) + if err != nil { + return err + } + for _, m := range members { + if strings.EqualFold(m.Email, email) { + _, err := a.executeActionsEmail(ctx, m.UserID, []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}, a.cfg.InviteRedirectURI) + return err + } + } + return ErrUserNotFound +} diff --git a/internal/keycloak/mock.go b/internal/keycloak/mock.go index 060798b..585ff06 100644 --- a/internal/keycloak/mock.go +++ b/internal/keycloak/mock.go @@ -24,6 +24,7 @@ type Mock struct { // seed an empty slice for an org with no members. Members map[string][]OrgMember Invites []MemberInviteInput // every InviteMember call that sent a mail + Resent []string // every ResendInvite call that found the member } func NewMock() *Mock { @@ -84,6 +85,27 @@ func (m *Mock) InviteMember(_ context.Context, in MemberInviteInput) (*MemberInv return &MemberInviteResult{UserID: userID, Status: InviteStatusInvited, Created: !created}, nil } +func (m *Mock) ResendInvite(_ context.Context, slug, email string) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.FailNext != nil { + err := m.FailNext + m.FailNext = nil + return err + } + members, ok := m.Members[slug] + if !ok { + return ErrOrgNotFound + } + for _, mem := range members { + if strings.EqualFold(mem.Email, email) { + m.Resent = append(m.Resent, email) + return nil + } + } + return ErrUserNotFound +} + func (m *Mock) SyncTenantStatus(_ context.Context, slug, status string) error { m.mu.Lock() defer m.mu.Unlock() diff --git a/internal/server/admin.go b/internal/server/admin.go new file mode 100644 index 0000000..49ae7c4 --- /dev/null +++ b/internal/server/admin.go @@ -0,0 +1,296 @@ +package server + +import ( + "context" + "errors" + "net/http" + "net/mail" + "strconv" + "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" +) + +// Staff administration (route group "admin", granted to the portal's service +// client only). The portal checks the staff member's realm role and passes +// who they are in X-Staff-Subject / X-Staff-Email, so every change lands in +// the audit log under the person, not under the portal. + +const ( + headerStaffSubject = "X-Staff-Subject" + headerStaffEmail = "X-Staff-Email" + activityWindow = 30 * 24 * time.Hour +) + +// staffActor is the staff member a request acts for: only honoured from a +// client that holds the admin group, so a product client cannot claim to be +// staff by setting a header. +func (s *Server) staffActor(r *http.Request) (subject, email string, ok bool) { + if r == nil { + return "", "", false + } + subject = strings.TrimSpace(r.Header.Get(headerStaffSubject)) + if subject == "" { + return "", "", false + } + p, has := authn.PrincipalFrom(r.Context()) + if !has || p.IsUser() || !s.Authz.Allowed(p.ClientID, "admin") { + return "", "", false + } + return subject, strings.TrimSpace(r.Header.Get(headerStaffEmail)), true +} + +type adminTenant struct { + store.Tenant + Activity store.TenantActivity `json:"activity"` +} + +// adminListTenants is GET /v1/admin/tenants?q=&status=&kind=&cursor=&limit=. +func (s *Server) adminListTenants(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + f := store.TenantFilter{Status: q.Get("status"), Kind: q.Get("kind"), Query: q.Get("q"), Cursor: q.Get("cursor")} + if v := q.Get("limit"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 1 || n > 500 { + writeError(w, http.StatusBadRequest, "invalid_limit", "limit must be 1..500") + return + } + f.Limit = n + } + if len(f.Query) > 100 { + writeError(w, http.StatusBadRequest, "invalid_query", "q must be at most 100 chars") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + tenants, next, err := s.Store.ListTenants(ctx, f) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + ids := make([]string, len(tenants)) + for i, t := range tenants { + ids[i] = t.ID + } + act, err := s.Store.TenantActivity(ctx, ids, time.Now().UTC().Add(-activityWindow)) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + items := make([]adminTenant, len(tenants)) + for i, t := range tenants { + a, ok := act[t.ID] + if !ok { + a = store.TenantActivity{Usage: map[string]float64{}} + } + items[i] = adminTenant{Tenant: t, Activity: a} + } + writeJSON(w, http.StatusOK, map[string]any{"items": items, "next_cursor": next}) +} + +type adminTenantDetail struct { + Tenant store.Tenant `json:"tenant"` + Activity store.TenantActivity `json:"activity"` + Entitlements []store.TenantProduct `json:"entitlements"` + Subscriptions []store.Subscription `json:"subscriptions"` + Licences []store.Licence `json:"licences"` + Members []keycloak.OrgMember `json:"members"` + MembersError string `json:"members_error,omitempty"` + Audit []store.AuditEvent `json:"audit"` +} + +// adminGetTenant is GET /v1/admin/tenants/{id}: everything staff need on one +// page. Keycloak is best effort; its failure is reported, not fatal. +func (s *Server) adminGetTenant(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + t, err := s.Store.GetTenant(ctx, r.PathValue("id")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + out := adminTenantDetail{Tenant: *t, Members: []keycloak.OrgMember{}} + act, err := s.Store.TenantActivity(ctx, []string{t.ID}, time.Now().UTC().Add(-activityWindow)) + if err == nil { + out.Activity = act[t.ID] + } + if out.Activity.Usage == nil { + out.Activity.Usage = map[string]float64{} + } + if out.Entitlements, err = s.Store.ListTenantProducts(ctx, t.ID); err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if out.Subscriptions, err = s.Store.ListSubscriptions(ctx, t.ID); err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if out.Licences, err = s.Store.ListLicences(ctx, t.ID); err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if out.Audit, _, err = s.Store.ListAudit(ctx, store.AuditFilter{TenantID: t.ID, Limit: 25}); err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if s.Keycloak != nil { + members, merr := s.Keycloak.ListOrgMembers(ctx, t.Slug) + switch { + case merr == nil: + out.Members = members + case errors.Is(merr, keycloak.ErrOrgNotFound): + out.MembersError = "no organization yet" + default: + out.MembersError = merr.Error() + } + } + writeJSON(w, http.StatusOK, out) +} + +type extendTrialReq struct { + Days int `json:"days"` +} + +// adminExtendTrial is POST /v1/admin/tenants/{id}/trial {"days": n}. The new +// end is n days after the later of now and the current end; trial +// entitlements move with it, and a tenant that the expired trial had made +// read-only goes back to trial. +func (s *Server) adminExtendTrial(w http.ResponseWriter, r *http.Request) { + var in extendTrialReq + if !decodeJSON(w, r, &in) { + return + } + if in.Days < 1 || in.Days > 90 { + writeError(w, http.StatusBadRequest, "invalid_days", "days must be 1..90") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, err := s.Store.GetTenant(ctx, r.PathValue("id")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + now := time.Now().UTC() + switch t.Status { + case store.StatusTrial: + case store.StatusRestricted, store.StatusFrozen, store.StatusHalted: + // Only when the expired trial is the reason: the trial end has passed + // and the tenant never had a subscription (a customer who stopped + // paying is not extended from here). + if t.TrialEndsAt == nil || t.TrialEndsAt.After(now) || s.hasSubscriptions(ctx, t.ID) { + writeError(w, http.StatusConflict, "not_a_trial", "tenant is "+t.Status+" for a reason other than an expired trial") + return + } + default: + writeError(w, http.StatusConflict, "not_a_trial", "only a trial (or a tenant stopped by an expired trial) can be extended") + return + } + base := now + if t.TrialEndsAt != nil && t.TrialEndsAt.After(now) { + base = *t.TrialEndsAt + } + end := base.Add(time.Duration(in.Days) * 24 * time.Hour) + previous := t.TrialEndsAt + t, err = s.Store.UpdateTenant(ctx, t.ID, store.TenantUpdate{TrialEndsAt: &end}) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + tps, err := s.Store.ListTenantProducts(ctx, t.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + for _, tp := range tps { + if tp.ExpiresAt == nil || tp.Config["source"] != "trial" { + continue + } + tp.ExpiresAt, tp.Enabled = &end, true + if _, err := s.Store.UpsertTenantProduct(ctx, tp); err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + } + if t.Status != store.StatusTrial { + if t, err = s.transition(ctx, r, t, store.StatusTrial, "staff:trial_extended"); err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + } + meta := map[string]interface{}{"days": in.Days, "trial_ends_at": end} + if previous != nil { + meta["previous_trial_ends_at"] = *previous + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "tenant.trial_extended", TargetID: t.ID, TargetType: "tenant", TargetName: t.Slug, + ActorType: "service", Metadata: meta, + }) + writeJSON(w, http.StatusOK, t) +} + +// hasSubscriptions reports whether the tenant ever had a subscription. An +// error counts as yes, so a failed lookup never unlocks a paying customer. +func (s *Server) hasSubscriptions(ctx context.Context, tenantID string) bool { + subs, err := s.Store.ListSubscriptions(ctx, tenantID) + return err != nil || len(subs) > 0 +} + +type resendInviteReq struct { + Email string `json:"email"` +} + +// adminResendInvite is POST /v1/admin/tenants/{id}/invites/resend {"email"}. +func (s *Server) adminResendInvite(w http.ResponseWriter, r *http.Request) { + var in resendInviteReq + 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 { + writeError(w, http.StatusBadRequest, "invalid_email", "email must be a bare, valid address") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + t, err := s.Store.GetTenant(ctx, r.PathValue("id")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if s.Keycloak == nil { + writeError(w, http.StatusServiceUnavailable, "keycloak_unavailable", "no identity provider configured") + return + } + if err := s.Keycloak.ResendInvite(ctx, t.Slug, in.Email); err != nil { + switch { + case errors.Is(err, keycloak.ErrOrgNotFound): + writeError(w, http.StatusConflict, "org_not_provisioned", "tenant has no Keycloak organization yet") + case errors.Is(err, keycloak.ErrUserNotFound): + writeError(w, http.StatusNotFound, "not_a_member", "no member with that email in this tenant") + default: + s.writeKeycloakError(w, t.ID, "resend invite", err) + } + return + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "user.invite_resent", TargetID: in.Email, TargetType: "user", TargetName: in.Email, + ActorType: "service", + }) + writeJSON(w, http.StatusAccepted, map[string]string{"status": "sent", "email": in.Email}) +} diff --git a/internal/server/admin_test.go b/internal/server/admin_test.go new file mode 100644 index 0000000..c71049d --- /dev/null +++ b/internal/server/admin_test.go @@ -0,0 +1,177 @@ +package server_test + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +func TestAdminListTenants_searchAndActivity(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + other := newTenant(t, h, "globex-werke") + ev := map[string]any{"idempotency_key": "adm-1", "tenant_id": other.ID, "product": "pruefwerk", "metric": "scan.completed", "quantity": 2, + "occurred_at": time.Now().UTC().Format(time.RFC3339)} + if resp, raw := h.do("POST", "/v1/usage/events", ev); resp.StatusCode != 202 { + t.Fatalf("usage: %d %s", resp.StatusCode, raw) + } + + resp, raw := h.do("GET", "/v1/admin/tenants?q=GLOBEX", nil) + if resp.StatusCode != 200 { + t.Fatalf("list: %d %s", resp.StatusCode, raw) + } + var out struct { + Items []struct { + Slug string `json:"slug"` + Activity struct { + Usage map[string]float64 `json:"usage"` + LastActivityAt *time.Time `json:"last_activity_at"` + } `json:"activity"` + } `json:"items"` + } + if err := json.Unmarshal(raw, &out); err != nil { + t.Fatal(err) + } + if len(out.Items) != 1 || out.Items[0].Slug != "globex-werke" { + t.Fatalf("search: %s", raw) + } + if out.Items[0].Activity.Usage["scan.completed"] != 2 || out.Items[0].Activity.LastActivityAt == nil { + t.Fatalf("activity: %s", raw) + } + + // no filter: both tenants, activity present (possibly empty) for each + _, raw = h.do("GET", "/v1/admin/tenants", nil) + if !strings.Contains(string(raw), `"acme"`) || !strings.Contains(string(raw), `"usage":{}`) { + t.Fatalf("unfiltered: %s", raw) + } + // wildcards in the query are literal + _, raw = h.do("GET", "/v1/admin/tenants?q=%25", nil) + if !strings.Contains(string(raw), `"items":[]`) { + t.Fatalf("wildcard matched: %s", raw) + } + if resp, _ := h.do("GET", "/v1/admin/tenants?limit=0", nil); resp.StatusCode != 400 { + t.Fatalf("limit: %d", resp.StatusCode) + } + if resp, _ := h.do("GET", "/v1/admin/tenants?q="+strings.Repeat("x", 101), nil); resp.StatusCode != 400 { + t.Fatalf("long q: %d", resp.StatusCode) + } + }) +} + +func TestAdminGetTenant_detail(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + h.kcMock.Members["acme"] = []keycloak.OrgMember{{UserID: "u1", Email: "it@acme.test", OrgRoles: []string{"IT_ADMIN"}}} + resp, raw := h.do("GET", "/v1/admin/tenants/"+h.tenant.ID, nil) + if resp.StatusCode != 200 { + t.Fatalf("detail: %d %s", resp.StatusCode, raw) + } + for _, want := range []string{`"tenant":{`, `"entitlements":`, `"subscriptions":`, `"licences":`, `"it@acme.test"`, `"audit":`} { + if !strings.Contains(string(raw), want) { + t.Fatalf("missing %s in %s", want, raw) + } + } + // no organization yet: members empty, reason given + other := newTenant(t, h, "no-org") + _, raw = h.do("GET", "/v1/admin/tenants/"+other.ID, nil) + if !strings.Contains(string(raw), `"members":[]`) || !strings.Contains(string(raw), "no organization yet") { + t.Fatalf("no org: %s", raw) + } + if resp, _ := h.do("GET", "/v1/admin/tenants/00000000-0000-0000-0000-00000000dead", nil); resp.StatusCode != 404 { + t.Fatalf("unknown: %d", resp.StatusCode) + } + }) +} + +func TestAdminExtendTrial(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + ctx := context.Background() + tn := newTenant(t, h, "trial-co") + end := time.Now().UTC().Add(3 * 24 * time.Hour) + if _, err := h.store.UpdateTenant(ctx, tn.ID, store.TenantUpdate{Status: ptr("trial"), TrialEndsAt: &end}); err != nil { + t.Fatal(err) + } + if _, err := h.store.UpsertTenantProduct(ctx, store.TenantProduct{TenantID: tn.ID, Product: "pruefwerk", Enabled: true, + Config: map[string]interface{}{"source": "trial"}, ExpiresAt: &end}); err != nil { + t.Fatal(err) + } + + if resp, _ := h.do("POST", "/v1/admin/tenants/"+tn.ID+"/trial", map[string]any{"days": 0}); resp.StatusCode != 400 { + t.Fatalf("days 0: %d", resp.StatusCode) + } + resp, raw := h.do("POST", "/v1/admin/tenants/"+tn.ID+"/trial", map[string]any{"days": 7}) + if resp.StatusCode != 200 { + t.Fatalf("extend: %d %s", resp.StatusCode, raw) + } + got, _ := h.store.GetTenant(ctx, tn.ID) + want := end.Add(7 * 24 * time.Hour) + if got.TrialEndsAt == nil || got.TrialEndsAt.Sub(want).Abs() > time.Second { + t.Fatalf("trial end %v, want %v", got.TrialEndsAt, want) + } + tps, _ := h.store.ListTenantProducts(ctx, tn.ID) + if len(tps) != 1 || tps[0].ExpiresAt.Sub(want).Abs() > time.Second { + t.Fatalf("entitlement not moved: %+v", tps) + } + items, _, _ := h.store.ListAudit(ctx, store.AuditFilter{TenantID: tn.ID, Action: "tenant.trial_extended"}) + if len(items) != 1 { + t.Fatalf("audit: %+v", items) + } + + // an expired trial that made the tenant read-only goes back to trial + past := time.Now().UTC().Add(-2 * 24 * time.Hour) + if _, err := h.store.UpdateTenant(ctx, tn.ID, store.TenantUpdate{Status: ptr("restricted"), TrialEndsAt: &past}); err != nil { + t.Fatal(err) + } + if resp, raw := h.do("POST", "/v1/admin/tenants/"+tn.ID+"/trial", map[string]any{"days": 5}); resp.StatusCode != 200 || !strings.Contains(string(raw), `"status":"trial"`) { + t.Fatalf("restricted: %d %s", resp.StatusCode, raw) + } + got, _ = h.store.GetTenant(ctx, tn.ID) + if d := time.Until(*got.TrialEndsAt); d < 4*24*time.Hour || d > 5*24*time.Hour+time.Minute { + t.Fatalf("restart from now: %v", d) + } + + // an active customer is not a trial + if _, err := h.store.UpdateTenant(ctx, tn.ID, store.TenantUpdate{Status: ptr("active")}); err != nil { + t.Fatal(err) + } + if resp, _ := h.do("POST", "/v1/admin/tenants/"+tn.ID+"/trial", map[string]any{"days": 5}); resp.StatusCode != http.StatusConflict { + t.Fatalf("active: %d", resp.StatusCode) + } + // restricted for non-payment (no trial end) is not a trial either + if _, err := h.store.UpdateTenant(ctx, h.tenant.ID, store.TenantUpdate{Status: ptr("restricted")}); err != nil { + t.Fatal(err) + } + if resp, _ := h.do("POST", "/v1/admin/tenants/"+h.tenant.ID+"/trial", map[string]any{"days": 5}); resp.StatusCode != http.StatusConflict { + t.Fatalf("non-trial restricted: %d", resp.StatusCode) + } + if resp, _ := h.do("POST", "/v1/admin/tenants/00000000-0000-0000-0000-00000000dead/trial", map[string]any{"days": 5}); resp.StatusCode != 404 { + t.Fatalf("unknown: %d", resp.StatusCode) + } + }) +} + +func TestAdminResendInvite(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + h.kcMock.Members["acme"] = []keycloak.OrgMember{{UserID: "u1", Email: "it@acme.test"}} + if resp, raw := h.do("POST", "/v1/admin/tenants/"+h.tenant.ID+"/invites/resend", map[string]any{"email": " IT@acme.test "}); resp.StatusCode != 202 { + t.Fatalf("resend: %d %s", resp.StatusCode, raw) + } + if len(h.kcMock.Resent) != 1 || h.kcMock.Resent[0] != "it@acme.test" { + t.Fatalf("mock: %v", h.kcMock.Resent) + } + if resp, _ := h.do("POST", "/v1/admin/tenants/"+h.tenant.ID+"/invites/resend", map[string]any{"email": "nobody@acme.test"}); resp.StatusCode != 404 { + t.Fatalf("non-member: %d", resp.StatusCode) + } + if resp, _ := h.do("POST", "/v1/admin/tenants/"+h.tenant.ID+"/invites/resend", map[string]any{"email": "not an email"}); resp.StatusCode != 400 { + t.Fatalf("bad email: %d", resp.StatusCode) + } + other := newTenant(t, h, "no-org-2") + if resp, _ := h.do("POST", "/v1/admin/tenants/"+other.ID+"/invites/resend", map[string]any{"email": "a@b.test"}); resp.StatusCode != 409 { + t.Fatalf("no org: %d", resp.StatusCode) + } + }) +} diff --git a/internal/server/authz.go b/internal/server/authz.go index b62e849..67b50c5 100644 --- a/internal/server/authz.go +++ b/internal/server/authz.go @@ -67,6 +67,8 @@ func (a *Authz) Allowed(azp, group string) bool { // routeGroup classifies a request. Keep in sync with NewRouter. func routeGroup(method, path string) string { switch { + case strings.HasPrefix(path, "/v1/admin/"): + return "admin" case strings.HasPrefix(path, "/v1/internal/entitlements/"): return "entitlements" case strings.HasPrefix(path, "/v1/internal/api-keys/verify"): diff --git a/internal/server/authz_middleware_test.go b/internal/server/authz_middleware_test.go index 5471ffa..8b0e29a 100644 --- a/internal/server/authz_middleware_test.go +++ b/internal/server/authz_middleware_test.go @@ -61,3 +61,40 @@ func TestLogAuthz(t *testing.T) { t.Fatalf("rules must be logged: %s", buf.String()) } } + +func TestStaffActor_onlyFromAdminClients(t *testing.T) { + s := &Server{Authz: ParseAuthzRules("portal-svc:admin,tenants;pruefwerk-svc:tenants.read")} + req := func(client string, user bool) *http.Request { + r := httptest.NewRequest("POST", "/v1/admin/tenants/x/trial", nil) + r.Header.Set("X-Staff-Subject", "staff-1") + r.Header.Set("X-Staff-Email", "ops@breakpilot.com") + p := &authn.Principal{Subject: "svc", ClientID: client} + if user { + p.TenantID = "t1" // a user token carries tenant context + } + return r.WithContext(authn.WithPrincipal(r.Context(), p)) + } + if sub, email, ok := s.staffActor(req("portal-svc", false)); !ok || sub != "staff-1" || email != "ops@breakpilot.com" { + t.Fatalf("admin client: %v %q %q", ok, sub, email) + } + if _, _, ok := s.staffActor(req("portal-svc", true)); ok { + t.Fatal("a user token must not claim a staff actor") + } + if _, _, ok := s.staffActor(req("pruefwerk-svc", false)); ok { + t.Fatal("a non-admin client must not claim a staff actor") + } + if _, _, ok := s.staffActor(httptest.NewRequest("GET", "/", nil)); ok { + t.Fatal("no header, no principal") + } + r := httptest.NewRequest("GET", "/", nil) + r.Header.Set("X-Staff-Subject", "staff-1") + if _, _, ok := s.staffActor(r); ok { + t.Fatal("header without a principal") + } + if _, _, ok := s.staffActor(nil); ok { + t.Fatal("nil request") + } + if g := routeGroup("GET", "/v1/admin/tenants"); g != "admin" { + t.Fatalf("route group %q", g) + } +} diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index 99d0be8..d293867 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -48,6 +48,11 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"GET", "/v1/tenants?limit=10"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/members"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/invites"}, + {"GET", "/v1/admin/tenants?q=acme"}, + {"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001"}, + {"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/trial"}, + {"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/invites/resend"}, + {"GET", "/v1/admin/audit?limit=10"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/status"}, {"POST", "/v1/internal/entitlements/check"}, {"POST", "/v1/internal/erp/webhook"}, diff --git a/internal/server/server.go b/internal/server/server.go index 6ed9f80..9fdf871 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -144,6 +144,13 @@ func NewRouter(s *Server) http.Handler { // JWT subject belong to, with which org_roles and entitlements. mux.HandleFunc("GET /v1/users/{id}/memberships", s.getUserMemberships) + // Staff administration (portal /admin; group "admin"). + mux.HandleFunc("GET /v1/admin/tenants", s.adminListTenants) + mux.HandleFunc("GET /v1/admin/tenants/{id}", s.adminGetTenant) + mux.HandleFunc("POST /v1/admin/tenants/{id}/trial", s.adminExtendTrial) + mux.HandleFunc("POST /v1/admin/tenants/{id}/invites/resend", s.adminResendInvite) + mux.HandleFunc("GET /v1/admin/audit", s.listAudit) + root.Handle("/", s.requireAuth(s.requireAuthz(mux))) return logRequest(s.Log)(root) } diff --git a/internal/server/tenants.go b/internal/server/tenants.go index 198fd42..76432e4 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -479,6 +479,10 @@ func (s *Server) emitAudit(ctx context.Context, r *http.Request, ev store.AuditE if r != nil { ev.SourceIP = clientIP(r) ev.UserAgent = r.UserAgent() + // A change made from the staff admin area is attributed to the person. + if sub, email, ok := s.staffActor(r); ok { + ev.ActorID, ev.ActorName, ev.ActorType = sub, email, "staff" + } } else if ev.ActorType == "" { ev.ActorType = "system" } diff --git a/internal/store/memory.go b/internal/store/memory.go index 09ee9d9..9101020 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -3,6 +3,7 @@ package store import ( "context" "sort" + "strings" "sync" "time" @@ -214,6 +215,12 @@ func (m *Memory) ListTenants(_ context.Context, f TenantFilter) ([]Tenant, strin if f.Kind != "" && t.Kind != f.Kind { continue } + if q := strings.ToLower(strings.TrimSpace(f.Query)); q != "" && + !strings.Contains(strings.ToLower(t.Slug), q) && + !strings.Contains(strings.ToLower(t.Name), q) && + !strings.Contains(strings.ToLower(t.AdminEmail), q) { + continue + } // keyset: only rows strictly after (cAt, cID) if f.Cursor != "" && t.CreatedAt.Before(cAt) || (f.Cursor != "" && t.CreatedAt.Equal(cAt) && t.ID <= cID) { continue @@ -234,6 +241,43 @@ func (m *Memory) ListTenants(_ context.Context, f TenantFilter) ([]Tenant, strin return all, next, nil } +func (m *Memory) TenantActivity(_ context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error) { + m.mu.RLock() + defer m.mu.RUnlock() + want := map[string]bool{} + for _, id := range tenantIDs { + want[id] = true + } + out := map[string]TenantActivity{} + get := func(id string) TenantActivity { + a, ok := out[id] + if !ok { + a = TenantActivity{Usage: map[string]float64{}} + } + return a + } + for _, u := range m.usage { + if !want[u.TenantID] || u.OccurredAt.Before(since) { + continue + } + a := get(u.TenantID) + a.Usage[u.Metric] += u.Quantity + out[u.TenantID] = a + } + for _, ev := range m.audit { + if !want[ev.TenantID] { + continue + } + a := get(ev.TenantID) + if a.LastActivityAt == nil || ev.CreatedAt.After(*a.LastActivityAt) { + at := ev.CreatedAt + a.LastActivityAt = &at + } + out[ev.TenantID] = a + } + return out, nil +} + // ─── products ───────────────────────────────────────────────────────────── func (m *Memory) ListProducts(_ context.Context, includeDisabled bool) ([]Product, error) { diff --git a/internal/store/postgres.go b/internal/store/postgres.go index 7352725..fa34678 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -520,6 +520,11 @@ func (p *Postgres) ListTenants(ctx context.Context, f TenantFilter) ([]Tenant, s if f.Kind != "" { add("kind = $%d::tenant_kind", f.Kind) } + if q := strings.TrimSpace(f.Query); q != "" { + args = append(args, "%"+likeEscape(q)+"%") + n := len(args) + where = append(where, fmt.Sprintf("(slug ILIKE $%d OR name ILIKE $%d OR COALESCE(admin_email, '') ILIKE $%d)", n, n, n)) + } if f.Cursor != "" { args = append(args, cAt, cID) where = append(where, fmt.Sprintf("(created_at, id::text) > ($%d, $%d)", len(args)-1, len(args))) @@ -614,3 +619,65 @@ func (p *Postgres) ListProducts(ctx context.Context, includeDisabled bool) ([]Pr func (p *Postgres) GetProduct(ctx context.Context, key string) (*Product, error) { return scanProduct(p.pool.QueryRow(ctx, productSelect+`WHERE key = $1`, key)) } + +// likeEscape escapes the LIKE wildcards in user input (the default escape is \). +func likeEscape(s string) string { + return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s) +} + +func (p *Postgres) TenantActivity(ctx context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error) { + out := map[string]TenantActivity{} + if len(tenantIDs) == 0 { + return out, nil + } + get := func(id string) TenantActivity { + a, ok := out[id] + if !ok { + a = TenantActivity{Usage: map[string]float64{}} + } + return a + } + rows, err := p.pool.Query(ctx, ` + SELECT tenant_id::text, metric, SUM(quantity) + FROM usage_events + WHERE tenant_id::text = ANY($1) AND occurred_at >= $2 + GROUP BY tenant_id, metric`, tenantIDs, since) + if err != nil { + return nil, err + } + for rows.Next() { + var id, metric string + var total float64 + if err := rows.Scan(&id, &metric, &total); err != nil { + rows.Close() + return nil, err + } + a := get(id) + a.Usage[metric] = total + out[id] = a + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, err + } + rows, err = p.pool.Query(ctx, ` + SELECT tenant_id::text, MAX(created_at) + FROM audit_log + WHERE tenant_id::text = ANY($1) + GROUP BY tenant_id`, tenantIDs) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + var id string + var at time.Time + if err := rows.Scan(&id, &at); err != nil { + return nil, err + } + a := get(id) + a.LastActivityAt = &at + out[id] = a + } + return out, rows.Err() +} diff --git a/internal/store/store.go b/internal/store/store.go index f072495..a486b58 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -74,6 +74,9 @@ type Store interface { GetTenantByErpCustomerID(ctx context.Context, erpCustomerID string) (*Tenant, error) UpdateTenant(ctx context.Context, id string, in TenantUpdate) (*Tenant, error) ListTenants(ctx context.Context, f TenantFilter) ([]Tenant, string, error) // rows + next cursor ("" = none) + // TenantActivity returns usage totals since `since` and the latest audit + // time for each of the given tenants (tenants without either are absent). + TenantActivity(ctx context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error) // Products (catalog) ListProducts(ctx context.Context, includeDisabled bool) ([]Product, error) diff --git a/internal/store/types.go b/internal/store/types.go index 1e378d6..68c2a57 100644 --- a/internal/store/types.go +++ b/internal/store/types.go @@ -127,10 +127,20 @@ type Product struct { type TenantFilter struct { Status string Kind string + // Query matches slug, name or admin_email case-insensitively (substring). + Query string Limit int Cursor string } +// TenantActivity summarises what a tenant did since a point in time: usage +// totals per metric and the time of its latest audit entry. Staff views use it +// to list tenants without one query per tenant. +type TenantActivity struct { + Usage map[string]float64 `json:"usage"` + LastActivityAt *time.Time `json:"last_activity_at,omitempty"` +} + // Tenant status ladder (migration 0002; ERP/02). 'frozen' is legacy = restricted. const ( StatusDemo = "demo" diff --git a/openapi.yaml b/openapi.yaml index 2d9ed55..4b8e7c1 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -278,6 +278,128 @@ paths: "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } + /v1/admin/tenants: + get: + summary: Staff tenant list with search and 30-day activity. + description: | + Route group `admin` (the portal's service client). `q` matches slug, + name or admin email, case-insensitively. Each item is a Tenant plus + `activity`: usage totals per metric over the last 30 days and the time + of the latest audit entry. Changes made through the admin routes are + audited under the staff member named in `X-Staff-Subject` / + `X-Staff-Email`. + parameters: + - { in: query, name: q, schema: { type: string, maxLength: 100 } } + - { in: query, name: status, schema: { type: string } } + - { in: query, name: kind, schema: { type: string } } + - { in: query, name: cursor, schema: { type: string } } + - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 500 } } + responses: + "200": + description: One page of tenants. + content: + application/json: + schema: + type: object + properties: + items: + type: array + items: + allOf: + - { $ref: "#/components/schemas/Tenant" } + - type: object + properties: + activity: { $ref: "#/components/schemas/TenantActivity" } + next_cursor: { type: string } + "400": { $ref: "#/components/responses/BadRequest" } + + /v1/admin/tenants/{id}: + get: + summary: Everything staff need about one tenant. + description: | + Tenant, 30-day activity, entitlements, subscriptions, licences, the + latest 25 audit entries and the Keycloak organization members (best + effort: on failure `members` is empty and `members_error` says why). + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The tenant detail. + content: + application/json: + schema: + type: object + properties: + tenant: { $ref: "#/components/schemas/Tenant" } + activity: { $ref: "#/components/schemas/TenantActivity" } + entitlements: { type: array, items: { type: object } } + subscriptions: { type: array, items: { type: object } } + licences: { type: array, items: { type: object } } + members: { type: array, items: { type: object } } + members_error: { type: string } + audit: { type: array, items: { type: object } } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/admin/tenants/{id}/trial: + post: + summary: Extend a trial. + description: | + Moves the trial end `days` after the later of now and the current end, + moves trial entitlements with it, and returns a tenant that an + expired trial made read-only (and that never had a subscription) to + `trial`. Audited as `tenant.trial_extended`. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [days] + properties: + days: { type: integer, minimum: 1, maximum: 90 } + responses: + "200": + description: The updated tenant. + content: + application/json: { schema: { $ref: "#/components/schemas/Tenant" } } + "400": { $ref: "#/components/responses/BadRequest" } + "404": { $ref: "#/components/responses/NotFound" } + "409": { $ref: "#/components/responses/Conflict" } + + /v1/admin/tenants/{id}/invites/resend: + post: + summary: Send a member's invitation mail again. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [email] + properties: + email: { type: string, format: email } + responses: + "202": { description: Sent. } + "400": { $ref: "#/components/responses/BadRequest" } + "404": { $ref: "#/components/responses/NotFound" } + "409": { $ref: "#/components/responses/Conflict" } + + /v1/admin/audit: + get: + summary: The audit log across all tenants (same filters as /v1/audit). + parameters: + - { in: query, name: tenant_id, schema: { type: string } } + - { in: query, name: action, schema: { type: string } } + - { in: query, name: cursor, schema: { type: integer } } + - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 500 } } + responses: + "200": { description: One page of audit entries. } + "400": { $ref: "#/components/responses/BadRequest" } + /v1/entitlements: get: summary: List product entitlements for a tenant. @@ -983,6 +1105,14 @@ components: error: { type: string, example: invalid_input } message: { type: string } + TenantActivity: + type: object + properties: + usage: + type: object + additionalProperties: { type: number } + description: usage totals per metric over the last 30 days + last_activity_at: { type: string, format: date-time } Tenant: type: object required: [id, slug, name, status, kind, plan, created_at, updated_at] -- 2.54.1 From da6eef6d307b6749f22faf0a81cd0e67c6a0afa5 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 23 Sep 2026 19:35:05 +0200 Subject: [PATCH 2/2] 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 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- cmd/server/main.go | 20 +- go.mod | 11 + go.sum | 23 ++ internal/config/config.go | 16 ++ internal/server/documents.go | 368 +++++++++++++++++++++++++++ internal/server/documents_test.go | 174 +++++++++++++ internal/server/members.go | 9 +- internal/server/openapi_test.go | 4 + internal/server/server.go | 9 + internal/storage/storage.go | 153 +++++++++++ internal/storage/storage_test.go | 57 +++++ internal/store/memory.go | 4 + internal/store/memory_documents.go | 87 +++++++ internal/store/postgres_documents.go | 111 ++++++++ internal/store/store.go | 8 + internal/store/types.go | 25 ++ migrations/0008_documents.down.sql | 1 + migrations/0008_documents.up.sql | 23 ++ migrations/migrations_test.go | 4 +- openapi.yaml | 117 +++++++++ 20 files changed, 1218 insertions(+), 6 deletions(-) create mode 100644 internal/server/documents.go create mode 100644 internal/server/documents_test.go create mode 100644 internal/storage/storage.go create mode 100644 internal/storage/storage_test.go create mode 100644 internal/store/memory_documents.go create mode 100644 internal/store/postgres_documents.go create mode 100644 migrations/0008_documents.down.sql create mode 100644 migrations/0008_documents.up.sql diff --git a/cmd/server/main.go b/cmd/server/main.go index 52ae031..3722aaf 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -3,6 +3,7 @@ package main import ( "context" "errors" + "git.breakpilot.com/platform/tenant-registry/internal/storage" "log/slog" "net/http" "os" @@ -134,7 +135,24 @@ func main() { slog.Warn("LITELLM_MASTER_KEY not set — Werkpilot licences are issued without a LiteLLM key") } - app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys} + var objects storage.Objects + docCfg := storage.Config{Endpoint: cfg.DocumentsS3Endpoint, Region: cfg.DocumentsS3Region, Bucket: cfg.DocumentsS3Bucket, + AccessKey: cfg.DocumentsS3AccessKey, SecretKey: cfg.DocumentsS3SecretKey} + if docCfg.Configured() { + sctx, scancel := context.WithTimeout(context.Background(), 30*time.Second) + s3, serr := storage.NewS3(sctx, docCfg) + scancel() + if serr != nil { + // Documents are one feature; the registry keeps serving everything else. + logger.Error("document storage unavailable; document routes answer 503", "err", serr) + } else { + objects = s3 + logger.Info("document storage ready", "bucket", docCfg.Bucket) + } + } else { + logger.Warn("DOCUMENTS_S3_* not set; document routes answer 503") + } + app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys, Objects: objects} handler := server.NewRouter(app) srv := &http.Server{ Addr: cfg.Addr, diff --git a/go.mod b/go.mod index 427da2b..1ee1413 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( github.com/google/uuid v1.6.0 github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6 github.com/jackc/pgx/v5 v5.9.2 + github.com/minio/minio-go/v7 v7.0.95 github.com/testcontainers/testcontainers-go/modules/postgres v0.42.0 golang.org/x/crypto v0.55.0 ) @@ -29,21 +30,27 @@ require ( github.com/distribution/reference v0.6.0 // indirect github.com/docker/go-connections v0.6.0 // indirect github.com/docker/go-units v0.5.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect github.com/ebitengine/purego v0.10.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/go-ini/ini v1.67.0 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/go-openapi/jsonpointer v0.22.5 // indirect github.com/go-openapi/swag/jsonname v0.25.5 // indirect + github.com/goccy/go-json v0.10.5 // indirect github.com/gorilla/mux v1.8.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/klauspost/compress v1.18.7 // indirect + github.com/klauspost/cpuid/v2 v2.2.11 // indirect github.com/lib/pq v1.10.9 // indirect github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect github.com/magiconair/properties v1.8.10 // indirect + github.com/minio/crc64nvme v1.0.2 // indirect + github.com/minio/md5-simd v1.1.2 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/go-archive v0.3.0 // indirect github.com/moby/moby/api v1.54.1 // indirect @@ -57,13 +64,16 @@ require ( github.com/oasdiff/yaml3 v0.0.14 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.1 // indirect + github.com/philhofer/fwd v1.2.0 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect + github.com/rs/xid v1.6.0 // indirect github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect github.com/shirou/gopsutil/v4 v4.26.3 // indirect github.com/sirupsen/logrus v1.9.4 // indirect github.com/stretchr/testify v1.11.1 // indirect github.com/testcontainers/testcontainers-go v0.42.0 // indirect + github.com/tinylib/msgp v1.3.0 // indirect github.com/tklauser/go-sysconf v0.3.16 // indirect github.com/tklauser/numcpus v0.11.0 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect @@ -72,6 +82,7 @@ require ( go.opentelemetry.io/otel v1.41.0 // indirect go.opentelemetry.io/otel/metric v1.41.0 // indirect go.opentelemetry.io/otel/trace v1.41.0 // indirect + golang.org/x/net v0.57.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sync v0.22.0 // indirect golang.org/x/sys v0.47.0 // indirect diff --git a/go.sum b/go.sum index f517863..3d91ccb 100644 --- a/go.sum +++ b/go.sum @@ -39,12 +39,16 @@ github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pM github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vmaMAntpSFH5BFKE= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU= github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/getkin/kin-openapi v0.144.0 h1:hIRcTH+KjLfkLpYU6bSSfdFpi0fZi1fp+hSPi4aQu9Y= github.com/getkin/kin-openapi v0.144.0/go.mod h1:3BH9M9XDe/y9M5DSvEocVYAYq1w0qrhJHjC/vZi0AaY= +github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A= +github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -60,6 +64,8 @@ github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3U github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU= github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM= github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-migrate/migrate/v4 v4.19.1 h1:OCyb44lFuQfYXYLx1SCxPZQGU7mcaZ7gH9yH4jSFbBA= @@ -83,6 +89,9 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw= github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU= +github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -95,6 +104,12 @@ github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8S github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/mdelapenya/tlscert v0.2.0 h1:7H81W6Z/4weDvZBNOfQte5GpIMo0lGYEeWbkGp5LJHI= github.com/mdelapenya/tlscert v0.2.0/go.mod h1:O4njj3ELLnJjGdkN7M/vIVCpZ+Cf0L6muqOG4tLSl8o= +github.com/minio/crc64nvme v1.0.2 h1:6uO1UxGAD+kwqWWp7mBFsi5gAse66C4NXO8cmcVculg= +github.com/minio/crc64nvme v1.0.2/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= +github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= +github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= +github.com/minio/minio-go/v7 v7.0.95 h1:ywOUPg+PebTMTzn9VDsoFJy32ZuARN9zhB+K3IYEvYU= +github.com/minio/minio-go/v7 v7.0.95/go.mod h1:wOOX3uxS334vImCNRVyIDdXX9OsXDm89ToynKgqUKlo= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= github.com/moby/go-archive v0.3.0 h1:nos4BtzzUIqB406BgQnWGMI4qib9BZ8XUHU+ucv/n1c= @@ -123,6 +138,8 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8 github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= +github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= +github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -132,6 +149,8 @@ github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ= github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= github.com/shirou/gopsutil/v4 v4.26.3 h1:2ESdQt90yU3oXF/CdOlRCJxrP+Am1aBYubTMTfxJ1qc= @@ -149,6 +168,8 @@ github.com/testcontainers/testcontainers-go v0.42.0 h1:He3IhTzTZOygSXLJPMX7n44Xt github.com/testcontainers/testcontainers-go v0.42.0/go.mod h1:vZjdY1YmUA1qEForxOIOazfsrdyORJAbhi0bp8plN30= github.com/testcontainers/testcontainers-go/modules/postgres v0.42.0 h1:GCbb1ndrF7OTDiIvxXyItaDab4qkzTFJ48LKFdM7EIo= github.com/testcontainers/testcontainers-go/modules/postgres v0.42.0/go.mod h1:IRPBaI8jXdrNfD0e4Zm7Fbcgaz5shKxOQv4axiL09xs= +github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww= +github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0= github.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA= github.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI= github.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw= @@ -171,6 +192,8 @@ go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis= golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= diff --git a/internal/config/config.go b/internal/config/config.go index 3831255..47cc598 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -67,6 +67,15 @@ type Config struct { // LiteLLM virtual keys for Werkpilot licences (D6). Empty master key ⇒ // feature off, grants carry no LLM key. Budgets are USD per 30 days. + // Tenant documents (F2): S3-compatible bucket. Unset ⇒ document routes 503. + DocumentsS3Endpoint string + DocumentsS3Region string + DocumentsS3Bucket string + DocumentsS3AccessKey string + DocumentsS3SecretKey string + // DocumentsMaxBytes caps one upload (default 200 MiB). + DocumentsMaxBytes int64 + LiteLLMBaseURL string LiteLLMMasterKey string LiteLLMModels []string @@ -118,6 +127,13 @@ func Load() (*Config, error) { LicenceIssuer: getenv("LICENCE_ISSUER", "tenant-registry"), LicenceTTLDays: getint("LICENCE_TTL_DAYS", 30), + DocumentsS3Endpoint: os.Getenv("DOCUMENTS_S3_ENDPOINT"), + DocumentsS3Region: getenv("DOCUMENTS_S3_REGION", "nbg1"), + DocumentsS3Bucket: os.Getenv("DOCUMENTS_S3_BUCKET"), + DocumentsS3AccessKey: os.Getenv("DOCUMENTS_S3_ACCESS_KEY"), + DocumentsS3SecretKey: os.Getenv("DOCUMENTS_S3_SECRET_KEY"), + DocumentsMaxBytes: int64(getint("DOCUMENTS_MAX_MB", 200)) << 20, + LiteLLMBaseURL: getenv("LITELLM_BASE_URL", "https://llm.breakpilot.com"), LiteLLMMasterKey: os.Getenv("LITELLM_MASTER_KEY"), LiteLLMModels: getlist("LITELLM_MODELS", []string{"Qwen3-Coder-30B-A3B-Instruct", "gpt-oss-120b", "Qwen3.8-27B"}), diff --git a/internal/server/documents.go b/internal/server/documents.go new file mode 100644 index 0000000..3c3abb4 --- /dev/null +++ b/internal/server/documents.go @@ -0,0 +1,368 @@ +package server + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "net/http" + "path" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// Tenant documents (F2): files BreakPilot prepares for a tenant — conformity +// documents, reports — until breakpilot-compliance delivers them itself. +// Staff upload a draft and publish it (admin group); the tenant lists and +// downloads published ones (tenants.read, user tokens scoped to their tenant). + +const downloadTTL = 5 * time.Minute + +// allowedDocumentTypes maps an accepted extension to the stored content type. +var allowedDocumentTypes = map[string]string{ + ".pdf": "application/pdf", + ".zip": "application/zip", + ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".txt": "text/plain; charset=utf-8", + ".csv": "text/csv; charset=utf-8", + ".json": "application/json", + ".xml": "application/xml", +} + +// safeFilename keeps the base name, drops control and path characters, and +// bounds the length; "" when nothing usable is left. +func safeFilename(name string) string { + name = path.Base(strings.ReplaceAll(name, `\`, "/")) + name = strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f || r == '/' || r == '"' { + return -1 + } + return r + }, strings.TrimSpace(name)) + if utf8.RuneCountInString(name) > 150 { + ext := path.Ext(name) + if utf8.RuneCountInString(ext) > 10 { + ext = "" + } + stem := []rune(strings.TrimSuffix(name, ext)) + name = string(stem[:150-utf8.RuneCountInString(ext)]) + ext + } + if name == "." || name == ".." { + return "" + } + return name +} + +func (s *Server) documentsReady(w http.ResponseWriter) bool { + if s.Objects == nil { + writeError(w, http.StatusServiceUnavailable, "documents_unavailable", "document storage is not configured") + return false + } + return true +} + +// countingReader counts bytes and hashes them on the way to the bucket. +type countingReader struct { + r io.Reader + n int64 + hash io.Writer +} + +func (c *countingReader) Read(p []byte) (int, error) { + n, err := c.r.Read(p) + c.n += int64(n) + _, _ = c.hash.Write(p[:n]) + return n, err +} + +// adminUploadDocument is POST /v1/admin/tenants/{id}/documents, a +// multipart/form-data body with optional fields "title" and "description" +// before the "file" part. The file is streamed to the bucket, never buffered +// whole; the result is a draft. +func (s *Server) adminUploadDocument(w http.ResponseWriter, r *http.Request) { + if !s.documentsReady(w) { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute) + defer cancel() + t, err := s.Store.GetTenant(ctx, r.PathValue("id")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + max := s.cfg().DocumentsMaxBytes + if max <= 0 { + max = 200 << 20 + } + r.Body = http.MaxBytesReader(w, r.Body, max+1<<20) // + the multipart envelope + mr, err := r.MultipartReader() + if err != nil { + writeError(w, http.StatusBadRequest, "invalid_body", "expected multipart/form-data") + return + } + + var title, description string + var doc *store.Document + for { + part, perr := mr.NextPart() + if perr == io.EOF { + break + } + if perr != nil { + s.dropUpload(ctx, doc) + writeError(w, http.StatusBadRequest, "invalid_body", perr.Error()) + return + } + switch part.FormName() { + case "title", "description": + b, _ := io.ReadAll(io.LimitReader(part, 4<<10)) + if part.FormName() == "title" { + title = strings.TrimSpace(string(b)) + } else { + description = strings.TrimSpace(string(b)) + } + case "file": + if doc != nil { + s.dropUpload(ctx, doc) + writeError(w, http.StatusBadRequest, "invalid_body", "one file per upload") + return + } + name := safeFilename(part.FileName()) + ctype, ok := allowedDocumentTypes[strings.ToLower(path.Ext(name))] + if name == "" || !ok { + writeError(w, http.StatusUnsupportedMediaType, "unsupported_type", "allowed: pdf, zip, docx, xlsx, pptx, png, jpg, txt, csv, json, xml") + return + } + id := uuid.NewString() + key := "tenants/" + t.ID + "/" + id + "/" + name + h := sha256.New() + cr := &countingReader{r: part, hash: h} + if perr := s.Objects.Put(ctx, key, cr, -1, ctype); perr != nil { + _ = s.Objects.Delete(context.WithoutCancel(ctx), key) + var tooBig *http.MaxBytesError + if errors.As(perr, &tooBig) || cr.n > max { + writeError(w, http.StatusRequestEntityTooLarge, "too_large", "the file is larger than the upload limit") + return + } + s.Log.Error("document upload failed", "tenant_id", t.ID, "err", perr) + writeError(w, http.StatusBadGateway, "storage_failed", "the file could not be stored") + return + } + if cr.n > max { + _ = s.Objects.Delete(context.WithoutCancel(ctx), key) + writeError(w, http.StatusRequestEntityTooLarge, "too_large", "the file is larger than the upload limit") + return + } + doc = &store.Document{ID: id, TenantID: t.ID, Filename: name, ContentType: ctype, SizeBytes: cr.n, + SHA256: hex.EncodeToString(h.Sum(nil)), ObjectKey: key, Status: store.DocumentDraft} + default: + _, _ = io.Copy(io.Discard, io.LimitReader(part, 1<<20)) + } + } + if doc == nil { + writeError(w, http.StatusBadRequest, "missing_file", "a file part named \"file\" is required") + return + } + if title == "" { + title = strings.TrimSuffix(doc.Filename, path.Ext(doc.Filename)) + } + if utf8.RuneCountInString(title) > 200 || utf8.RuneCountInString(description) > 2000 { + s.dropUpload(ctx, doc) + writeError(w, http.StatusBadRequest, "invalid_input", "title ≤ 200 and description ≤ 2000 characters") + return + } + doc.Title, doc.Description = title, description + if sub, email, ok := s.staffActor(r); ok { + doc.UploadedBy = firstNonEmpty(email, sub) + } + created, err := s.Store.CreateDocument(ctx, *doc) + if err != nil { + s.dropUpload(ctx, doc) + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "document.uploaded", TargetID: created.ID, TargetType: "document", TargetName: created.Title, + ActorType: "service", Metadata: map[string]interface{}{"filename": created.Filename, "size_bytes": created.SizeBytes, "sha256": created.SHA256}, + }) + writeJSON(w, http.StatusCreated, created) +} + +// dropUpload removes an object stored for an upload that did not complete. +func (s *Server) dropUpload(ctx context.Context, d *store.Document) { + if d != nil { + _ = s.Objects.Delete(context.WithoutCancel(ctx), d.ObjectKey) + } +} + +func firstNonEmpty(v ...string) string { + for _, s := range v { + if s != "" { + return s + } + } + return "" +} + +// adminListDocuments is GET /v1/admin/tenants/{id}/documents: drafts included. +func (s *Server) adminListDocuments(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + t, err := s.Store.GetTenant(ctx, r.PathValue("id")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + docs, err := s.Store.ListDocuments(ctx, t.ID, false) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"items": docs}) +} + +// adminPublishDocument is POST /v1/admin/documents/{doc}/publish. Publishing +// makes the document visible to the tenant; publishing twice is harmless. +func (s *Server) adminPublishDocument(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + d, err := s.Store.GetDocument(ctx, r.PathValue("doc")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if d.Status == store.DocumentPublished { + writeJSON(w, http.StatusOK, d) + return + } + by := "" + if sub, email, ok := s.staffActor(r); ok { + by = firstNonEmpty(email, sub) + } + d, err = s.Store.PublishDocument(ctx, d.ID, by, s.now()) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: d.TenantID, Action: "document.published", TargetID: d.ID, TargetType: "document", TargetName: d.Title, + ActorType: "service", + }) + s.documentPublished(ctx, d) + writeJSON(w, http.StatusOK, d) +} + +// documentPublished is where F3 hangs the tenant notification. +func (s *Server) documentPublished(_ context.Context, _ *store.Document) {} + +// adminDeleteDocument is DELETE /v1/admin/documents/{doc}. +func (s *Server) adminDeleteDocument(w http.ResponseWriter, r *http.Request) { + if !s.documentsReady(w) { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + d, err := s.Store.GetDocument(ctx, r.PathValue("doc")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if err := s.Objects.Delete(ctx, d.ObjectKey); err != nil { + s.Log.Error("document object delete failed", "document_id", d.ID, "err", err) + writeError(w, http.StatusBadGateway, "storage_failed", "the file could not be deleted") + return + } + if err := s.Store.DeleteDocument(ctx, d.ID); err != nil && !errors.Is(err, store.ErrNotFound) { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: d.TenantID, Action: "document.deleted", TargetID: d.ID, TargetType: "document", TargetName: d.Title, + ActorType: "service", + }) + w.WriteHeader(http.StatusNoContent) +} + +// listTenantDocuments is GET /v1/tenants/{id}/documents: published only. +func (s *Server) listTenantDocuments(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + docs, err := s.Store.ListDocuments(ctx, t.ID, true) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"items": docs}) +} + +// downloadTenantDocument is GET /v1/tenants/{id}/documents/{doc}/download: +// a presigned URL valid for five minutes, and an audit entry naming who +// downloaded it (the user token's subject, or the person the portal names in +// X-Portal-User-Email). +func (s *Server) downloadTenantDocument(w http.ResponseWriter, r *http.Request) { + if !s.documentsReady(w) { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + d, err := s.Store.GetDocument(ctx, r.PathValue("doc")) + if err != nil || d.TenantID != t.ID || d.Status != store.DocumentPublished { + writeError(w, http.StatusNotFound, "not_found", "resource does not exist") + return + } + u, err := s.Objects.PresignGet(ctx, d.ObjectKey, d.Filename, downloadTTL) + if err != nil { + s.Log.Error("presign failed", "document_id", d.ID, "err", err) + writeError(w, http.StatusBadGateway, "storage_failed", "no download link could be made") + return + } + ev := store.AuditEvent{TenantID: t.ID, Action: "document.downloaded", TargetID: d.ID, TargetType: "document", TargetName: d.Title} + if p, has := authn.PrincipalFrom(r.Context()); has { + ev.ActorID, ev.ActorName, ev.ActorType = p.Subject, p.Email, "service" + if p.IsUser() { + ev.ActorType = "user" + } else if email := strings.TrimSpace(r.Header.Get("X-Portal-User-Email")); email != "" { + ev.ActorName, ev.ActorType = email, "user" + } + } + s.emitAudit(ctx, r, ev) + writeJSON(w, http.StatusOK, map[string]any{ + "url": u, "filename": d.Filename, "content_type": d.ContentType, + "expires_at": s.now().Add(downloadTTL), + }) +} diff --git a/internal/server/documents_test.go b/internal/server/documents_test.go new file mode 100644 index 0000000..e3c4095 --- /dev/null +++ b/internal/server/documents_test.go @@ -0,0 +1,174 @@ +package server_test + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "mime/multipart" + "net/http" + "strings" + "testing" + + "git.breakpilot.com/platform/tenant-registry/internal/storage" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +func upload(t *testing.T, h *testHarness, tenantID string, fields map[string]string, filename, content string) (*http.Response, []byte) { + t.Helper() + var buf bytes.Buffer + mw := multipart.NewWriter(&buf) + for _, k := range []string{"title", "description"} { + if v, ok := fields[k]; ok { + _ = mw.WriteField(k, v) + } + } + if filename != "" { + fw, _ := mw.CreateFormFile("file", filename) + _, _ = io.WriteString(fw, content) + } + _ = mw.Close() + req, _ := http.NewRequest("POST", h.srv.URL+"/v1/admin/tenants/"+tenantID+"/documents", &buf) + req.Header.Set("Content-Type", mw.FormDataContentType()) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + raw, _ := io.ReadAll(resp.Body) + return resp, raw +} + +func TestDocuments_uploadPublishDownloadDelete(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + objs := storage.NewMemory() + h.app.Objects = objs + content := "%PDF-1.7 conformity" + + resp, raw := upload(t, h, h.tenant.ID, map[string]string{"title": "CRA-Dossier", "description": "Q3"}, "../../Prüfbericht.pdf", content) + if resp.StatusCode != 201 { + t.Fatalf("upload: %d %s", resp.StatusCode, raw) + } + var d store.Document + _ = json.Unmarshal(raw, &d) + sum := sha256.Sum256([]byte(content)) + if d.Status != "draft" || d.Filename != "Prüfbericht.pdf" || d.SizeBytes != int64(len(content)) || d.SHA256 != hex.EncodeToString(sum[:]) || d.ContentType != "application/pdf" { + t.Fatalf("stored: %+v", d) + } + if len(objs.Objects) != 1 || strings.Contains(string(raw), "object_key") { + t.Fatalf("object not stored or key leaked: %d %s", len(objs.Objects), raw) + } + + // drafts are invisible to the tenant + _, raw = h.do("GET", "/v1/tenants/"+h.tenant.ID+"/documents", nil) + if !strings.Contains(string(raw), `"items":[]`) { + t.Fatalf("draft visible: %s", raw) + } + if resp, _ := h.do("GET", "/v1/tenants/"+h.tenant.ID+"/documents/"+d.ID+"/download", nil); resp.StatusCode != 404 { + t.Fatalf("draft downloadable: %d", resp.StatusCode) + } + // staff see it + _, raw = h.do("GET", "/v1/admin/tenants/"+h.tenant.ID+"/documents", nil) + if !strings.Contains(string(raw), d.ID) { + t.Fatalf("admin list: %s", raw) + } + + resp, raw = h.do("POST", "/v1/admin/documents/"+d.ID+"/publish", nil) + if resp.StatusCode != 200 || !strings.Contains(string(raw), `"status":"published"`) { + t.Fatalf("publish: %d %s", resp.StatusCode, raw) + } + if resp, _ := h.do("POST", "/v1/admin/documents/"+d.ID+"/publish", nil); resp.StatusCode != 200 { + t.Fatalf("publish twice: %d", resp.StatusCode) + } + _, raw = h.do("GET", "/v1/tenants/"+h.tenant.ID+"/documents", nil) + if !strings.Contains(string(raw), d.ID) { + t.Fatalf("published not listed: %s", raw) + } + resp, raw = h.do("GET", "/v1/tenants/"+h.tenant.ID+"/documents/"+d.ID+"/download", nil) + if resp.StatusCode != 200 || !strings.Contains(string(raw), `"url":"memory://`) || !strings.Contains(string(raw), "Pr%C3%BCfbericht.pdf") { + t.Fatalf("download: %d %s", resp.StatusCode, raw) + } + // another tenant cannot reach it + other := newTenant(t, h, "other-docs") + if resp, _ := h.do("GET", "/v1/tenants/"+other.ID+"/documents/"+d.ID+"/download", nil); resp.StatusCode != 404 { + t.Fatalf("cross-tenant download: %d", resp.StatusCode) + } + items, _, _ := h.store.ListAudit(context.Background(), store.AuditFilter{TenantID: h.tenant.ID}) + seen := map[string]bool{} + for _, a := range items { + seen[a.Action] = true + } + for _, a := range []string{"document.uploaded", "document.published", "document.downloaded"} { + if !seen[a] { + t.Fatalf("audit %s missing: %v", a, seen) + } + } + + if resp, _ := h.do("DELETE", "/v1/admin/documents/"+d.ID, nil); resp.StatusCode != 204 { + t.Fatalf("delete: %d", resp.StatusCode) + } + if len(objs.Objects) != 0 { + t.Fatal("object not deleted") + } + if resp, _ := h.do("DELETE", "/v1/admin/documents/"+d.ID, nil); resp.StatusCode != 404 { + t.Fatalf("delete twice: %d", resp.StatusCode) + } + if resp, _ := h.do("POST", "/v1/admin/documents/not-a-uuid/publish", nil); resp.StatusCode != 404 { + t.Fatalf("publish unknown: %d", resp.StatusCode) + } + }) +} + +func TestDocuments_uploadRules(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + objs := storage.NewMemory() + h.app.Objects = objs + + if resp, _ := upload(t, h, h.tenant.ID, nil, "tool.exe", "MZ"); resp.StatusCode != 415 { + t.Fatalf("exe: %d", resp.StatusCode) + } + if resp, _ := upload(t, h, h.tenant.ID, map[string]string{"title": "x"}, "", ""); resp.StatusCode != 400 { + t.Fatalf("no file: %d", resp.StatusCode) + } + // the title defaults to the file name without extension + resp, raw := upload(t, h, h.tenant.ID, nil, "Risikobewertung.docx", "PK") + if resp.StatusCode != 201 || !strings.Contains(string(raw), `"title":"Risikobewertung"`) { + t.Fatalf("default title: %d %s", resp.StatusCode, raw) + } + if resp, _ := upload(t, h, h.tenant.ID, map[string]string{"title": strings.Repeat("x", 201)}, "a.pdf", "x"); resp.StatusCode != 400 { + t.Fatalf("long title: %d", resp.StatusCode) + } + if len(objs.Objects) != 1 { + t.Fatalf("rejected upload left an object: %d", len(objs.Objects)) + } + // over the size limit + h.app.Cfg.DocumentsMaxBytes = 4 + if resp, _ := upload(t, h, h.tenant.ID, nil, "big.pdf", "123456789"); resp.StatusCode != 413 { + t.Fatalf("too large: %d", resp.StatusCode) + } + h.app.Cfg.DocumentsMaxBytes = 0 + // storage failure + objs.FailPut = errors.New("down") + if resp, _ := upload(t, h, h.tenant.ID, nil, "a.pdf", "x"); resp.StatusCode != 502 { + t.Fatalf("storage down: %d", resp.StatusCode) + } + objs.FailPut = nil + if resp, _ := upload(t, h, "00000000-0000-0000-0000-00000000dead", nil, "a.pdf", "x"); resp.StatusCode != 404 { + t.Fatalf("unknown tenant: %d", resp.StatusCode) + } + req, _ := http.NewRequest("POST", h.srv.URL+"/v1/admin/tenants/"+h.tenant.ID+"/documents", strings.NewReader("{}")) + req.Header.Set("Content-Type", "application/json") + if resp, err := http.DefaultClient.Do(req); err != nil || resp.StatusCode != 400 { + t.Fatalf("not multipart: %v %v", resp, err) + } + + // not configured + h.app.Objects = nil + if resp, _ := upload(t, h, h.tenant.ID, nil, "a.pdf", "x"); resp.StatusCode != 503 { + t.Fatalf("unconfigured: %d", resp.StatusCode) + } + }) +} diff --git a/internal/server/members.go b/internal/server/members.go index e83a129..04634a3 100644 --- a/internal/server/members.go +++ b/internal/server/members.go @@ -73,11 +73,14 @@ func (s *Server) tenantInScope(ctx context.Context, w http.ResponseWriter, r *ht // 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) { - if r.PathValue("sub") != "members" { + 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") - return } - s.listTenantMembers(w, r) } func (s *Server) listTenantMembers(w http.ResponseWriter, r *http.Request) { diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index d293867..8e5289c 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -53,6 +53,10 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/trial"}, {"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/invites/resend"}, {"GET", "/v1/admin/audit?limit=10"}, + {"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/documents"}, + {"POST", "/v1/admin/documents/00000000-0000-0000-0000-000000000002/publish"}, + {"DELETE", "/v1/admin/documents/00000000-0000-0000-0000-000000000002"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/documents/00000000-0000-0000-0000-000000000002/download"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/status"}, {"POST", "/v1/internal/entitlements/check"}, {"POST", "/v1/internal/erp/webhook"}, diff --git a/internal/server/server.go b/internal/server/server.go index 9fdf871..13636b4 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -6,6 +6,7 @@ package server import ( "errors" + "git.breakpilot.com/platform/tenant-registry/internal/storage" "log/slog" "net/http" "time" @@ -34,6 +35,7 @@ type Server struct { ERP *erp.Client // nil / disabled ⇒ outbox accumulates, reconcile idle Licences *licence.Signer // nil ⇒ licence endpoints return 503 LLMKeys *llmkeys.Client // nil / disabled ⇒ Werkpilot grants carry no LiteLLM key (D6) + Objects storage.Objects // nil ⇒ document routes answer 503 (F2) Now func() time.Time // injectable clock (tests); nil ⇒ time.Now } @@ -150,6 +152,13 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("POST /v1/admin/tenants/{id}/trial", s.adminExtendTrial) mux.HandleFunc("POST /v1/admin/tenants/{id}/invites/resend", s.adminResendInvite) mux.HandleFunc("GET /v1/admin/audit", s.listAudit) + mux.HandleFunc("GET /v1/admin/tenants/{id}/documents", s.adminListDocuments) + mux.HandleFunc("POST /v1/admin/tenants/{id}/documents", s.adminUploadDocument) + mux.HandleFunc("POST /v1/admin/documents/{doc}/publish", s.adminPublishDocument) + mux.HandleFunc("DELETE /v1/admin/documents/{doc}", s.adminDeleteDocument) + + // Tenant documents (F2): the list is a {sub} of tenantSubresource. + mux.HandleFunc("GET /v1/tenants/{id}/documents/{doc}/download", s.downloadTenantDocument) root.Handle("/", s.requireAuth(s.requireAuthz(mux))) return logRequest(s.Log)(root) diff --git a/internal/storage/storage.go b/internal/storage/storage.go new file mode 100644 index 0000000..9ae88c9 --- /dev/null +++ b/internal/storage/storage.go @@ -0,0 +1,153 @@ +// Package storage keeps tenant documents in S3-compatible object storage +// (Hetzner Object Storage in production, MinIO locally). The registry never +// serves file bytes itself: uploads are streamed to the bucket, downloads are +// short-lived presigned URLs the browser follows. +package storage + +import ( + "context" + "errors" + "fmt" + "io" + "net/url" + "strings" + "sync" + "time" + + "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" +) + +// ErrNotConfigured is returned by a nil store: document routes answer 503. +var ErrNotConfigured = errors.New("storage: object storage not configured") + +// Objects is what the document handlers need. +type Objects interface { + // Put streams r to key; size -1 means unknown (multipart upload). + Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error + // PresignGet returns a GET URL valid for ttl that downloads as filename. + PresignGet(ctx context.Context, key, filename string, ttl time.Duration) (string, error) + Delete(ctx context.Context, key string) error +} + +// Config for an S3 bucket. +type Config struct { + Endpoint string // https://nbg1.your-objectstorage.com + Region string // nbg1 + Bucket string + AccessKey string + SecretKey string +} + +// Configured reports whether every field needed for S3 is set. +func (c Config) Configured() bool { + return c.Endpoint != "" && c.Bucket != "" && c.AccessKey != "" && c.SecretKey != "" +} + +// S3 is Objects on an S3-compatible bucket. +type S3 struct { + client *minio.Client + bucket string +} + +// NewS3 connects and makes sure the bucket exists (created private, in the +// configured region: Hetzner refuses a CreateBucket without a matching +// location constraint). +func NewS3(ctx context.Context, cfg Config) (*S3, error) { + u, err := url.Parse(cfg.Endpoint) + if err != nil || u.Host == "" { + return nil, fmt.Errorf("storage: endpoint %q is not a URL", cfg.Endpoint) + } + client, err := minio.New(u.Host, &minio.Options{ + Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""), + Secure: u.Scheme != "http", + Region: cfg.Region, + }) + if err != nil { + return nil, fmt.Errorf("storage: client: %w", err) + } + exists, err := client.BucketExists(ctx, cfg.Bucket) + if err != nil { + return nil, fmt.Errorf("storage: bucket %s: %w", cfg.Bucket, err) + } + if !exists { + if err := client.MakeBucket(ctx, cfg.Bucket, minio.MakeBucketOptions{Region: cfg.Region}); err != nil { + return nil, fmt.Errorf("storage: create bucket %s: %w", cfg.Bucket, err) + } + } + return &S3{client: client, bucket: cfg.Bucket}, nil +} + +func (s *S3) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error { + _, err := s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{ContentType: contentType}) + return err +} + +func (s *S3) PresignGet(ctx context.Context, key, filename string, ttl time.Duration) (string, error) { + params := url.Values{} + params.Set("response-content-disposition", ContentDisposition(filename)) + u, err := s.client.PresignedGetObject(ctx, s.bucket, key, ttl, params) + if err != nil { + return "", err + } + return u.String(), nil +} + +func (s *S3) Delete(ctx context.Context, key string) error { + return s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}) +} + +// ContentDisposition is an attachment header with an ASCII fallback name and +// the UTF-8 name (RFC 6266 / 5987), so "Prüfbericht.pdf" survives. +func ContentDisposition(filename string) string { + ascii := strings.Map(func(r rune) rune { + if r < 0x20 || r > 0x7e || r == '"' || r == '\\' { + return '_' + } + return r + }, filename) + return fmt.Sprintf(`attachment; filename="%s"; filename*=UTF-8''%s`, ascii, url.PathEscape(filename)) +} + +// Memory is Objects in process memory, for tests and local development. +type Memory struct { + mu sync.Mutex + Objects map[string][]byte + Types map[string]string + FailPut error +} + +func NewMemory() *Memory { + return &Memory{Objects: map[string][]byte{}, Types: map[string]string{}} +} + +func (m *Memory) Put(_ context.Context, key string, r io.Reader, _ int64, contentType string) error { + if m.FailPut != nil { + return m.FailPut + } + b, err := io.ReadAll(r) + if err != nil { + return err + } + m.mu.Lock() + defer m.mu.Unlock() + m.Objects[key], m.Types[key] = b, contentType + return nil +} + +func (m *Memory) PresignGet(_ context.Context, key, filename string, ttl time.Duration) (string, error) { + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.Objects[key]; !ok { + return "", fmt.Errorf("storage: no object %s", key) + } + return "memory://" + key + "?filename=" + url.QueryEscape(filename) + "&ttl=" + ttl.String(), nil +} + +func (m *Memory) Delete(_ context.Context, key string) error { + m.mu.Lock() + defer m.mu.Unlock() + delete(m.Objects, key) + delete(m.Types, key) + return nil +} diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go new file mode 100644 index 0000000..08d0f85 --- /dev/null +++ b/internal/storage/storage_test.go @@ -0,0 +1,57 @@ +package storage + +import ( + "context" + "errors" + "strings" + "testing" + "time" +) + +func TestContentDisposition(t *testing.T) { + got := ContentDisposition(`Prüfbericht "Q3".pdf`) + want := `attachment; filename="Pr_fbericht _Q3_.pdf"; filename*=UTF-8''Pr%C3%BCfbericht%20%22Q3%22.pdf` + if got != want { + t.Fatalf("got %s\nwant %s", got, want) + } +} + +func TestConfigured(t *testing.T) { + if (Config{}).Configured() { + t.Fatal("empty config is configured") + } + if !(Config{Endpoint: "https://x", Bucket: "b", AccessKey: "a", SecretKey: "s"}).Configured() { + t.Fatal("full config not configured") + } +} + +func TestNewS3_rejectsBadEndpoint(t *testing.T) { + if _, err := NewS3(context.Background(), Config{Endpoint: "::nope", Bucket: "b", AccessKey: "a", SecretKey: "s"}); err == nil { + t.Fatal("bad endpoint accepted") + } +} + +func TestMemory(t *testing.T) { + ctx := context.Background() + m := NewMemory() + if err := m.Put(ctx, "k", strings.NewReader("hello"), -1, "text/plain"); err != nil { + t.Fatal(err) + } + if string(m.Objects["k"]) != "hello" || m.Types["k"] != "text/plain" { + t.Fatalf("stored %q %q", m.Objects["k"], m.Types["k"]) + } + u, err := m.PresignGet(ctx, "k", "a b.pdf", time.Minute) + if err != nil || !strings.Contains(u, "filename=a+b.pdf") { + t.Fatalf("presign %q %v", u, err) + } + if _, err := m.PresignGet(ctx, "missing", "x", time.Minute); err == nil { + t.Fatal("presign of a missing object") + } + if err := m.Delete(ctx, "k"); err != nil || len(m.Objects) != 0 { + t.Fatalf("delete %v", err) + } + m.FailPut = errors.New("boom") + if err := m.Put(ctx, "k", strings.NewReader("x"), 1, ""); err == nil { + t.Fatal("FailPut ignored") + } +} diff --git a/internal/store/memory.go b/internal/store/memory.go index 9101020..1f492b0 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -33,6 +33,8 @@ type Memory struct { outboxID int64 receipts map[string]time.Time licences map[string]*Licence + + documents map[string]*Document } type apiKeyWithHash struct { @@ -53,6 +55,8 @@ func NewMemory() *Memory { usageKey: make(map[string]int64), receipts: make(map[string]time.Time), licences: make(map[string]*Licence), + + documents: make(map[string]*Document), } now := time.Now().UTC() seed := &Tenant{ diff --git a/internal/store/memory_documents.go b/internal/store/memory_documents.go new file mode 100644 index 0000000..e9e92f1 --- /dev/null +++ b/internal/store/memory_documents.go @@ -0,0 +1,87 @@ +package store + +import ( + "context" + "sort" + "time" +) + +func (m *Memory) CreateDocument(_ context.Context, d Document) (*Document, error) { + m.mu.Lock() + defer m.mu.Unlock() + if d.ID == "" || d.ObjectKey == "" || d.Title == "" { + return nil, ErrInvalidInput + } + if _, ok := m.tenants[d.TenantID]; !ok { + return nil, ErrNotFound + } + for _, x := range m.documents { + if x.ID == d.ID || x.ObjectKey == d.ObjectKey { + return nil, ErrConflict + } + } + now := time.Now().UTC() + if d.Status == "" { + d.Status = DocumentDraft + } + d.CreatedAt, d.UpdatedAt = now, now + row := d + m.documents[d.ID] = &row + out := row + return &out, nil +} + +func (m *Memory) GetDocument(_ context.Context, id string) (*Document, error) { + m.mu.RLock() + defer m.mu.RUnlock() + d, ok := m.documents[id] + if !ok { + return nil, ErrNotFound + } + out := *d + return &out, nil +} + +func (m *Memory) ListDocuments(_ context.Context, tenantID string, publishedOnly bool) ([]Document, error) { + m.mu.RLock() + defer m.mu.RUnlock() + out := []Document{} + for _, d := range m.documents { + if d.TenantID != tenantID || (publishedOnly && d.Status != DocumentPublished) { + continue + } + out = append(out, *d) + } + sort.Slice(out, func(i, j int) bool { + if out[i].CreatedAt.Equal(out[j].CreatedAt) { + return out[i].ID > out[j].ID + } + return out[i].CreatedAt.After(out[j].CreatedAt) + }) + return out, nil +} + +func (m *Memory) PublishDocument(_ context.Context, id, by string, at time.Time) (*Document, error) { + m.mu.Lock() + defer m.mu.Unlock() + d, ok := m.documents[id] + if !ok { + return nil, ErrNotFound + } + if d.Status != DocumentPublished { + at = at.UTC() + d.Status, d.PublishedBy, d.PublishedAt, d.UpdatedAt = DocumentPublished, by, &at, at + } + out := *d + return &out, nil +} + +func (m *Memory) DeleteDocument(_ context.Context, id string) error { + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.documents[id]; !ok { + return ErrNotFound + } + delete(m.documents, id) + return nil +} diff --git a/internal/store/postgres_documents.go b/internal/store/postgres_documents.go new file mode 100644 index 0000000..9b246bc --- /dev/null +++ b/internal/store/postgres_documents.go @@ -0,0 +1,111 @@ +package store + +import ( + "context" + "errors" + "time" + + "github.com/jackc/pgx/v5" +) + +const documentSelect = ` +SELECT id::text, tenant_id::text, title, description, filename, content_type, size_bytes, sha256, + object_key, status, uploaded_by, COALESCE(published_by, ''), published_at, created_at, updated_at +FROM documents ` + +func scanDocument(row pgx.Row) (*Document, error) { + var d Document + if err := row.Scan(&d.ID, &d.TenantID, &d.Title, &d.Description, &d.Filename, &d.ContentType, &d.SizeBytes, &d.SHA256, + &d.ObjectKey, &d.Status, &d.UploadedBy, &d.PublishedBy, &d.PublishedAt, &d.CreatedAt, &d.UpdatedAt); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + return &d, nil +} + +func (p *Postgres) CreateDocument(ctx context.Context, d Document) (*Document, error) { + if d.ID == "" || d.ObjectKey == "" || d.Title == "" { + return nil, ErrInvalidInput + } + if d.Status == "" { + d.Status = DocumentDraft + } + _, err := p.pool.Exec(ctx, ` + INSERT INTO documents (id, tenant_id, title, description, filename, content_type, size_bytes, sha256, object_key, status, uploaded_by) + VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, + d.ID, d.TenantID, d.Title, d.Description, d.Filename, d.ContentType, d.SizeBytes, d.SHA256, d.ObjectKey, d.Status, d.UploadedBy) + switch { + case err == nil: + return p.GetDocument(ctx, d.ID) + case isFKViolation(err), isInvalidUUID(err): + return nil, ErrNotFound + case isUniqueViolation(err): + return nil, ErrConflict + case isCheckViolation(err): + return nil, ErrInvalidInput + default: + return nil, err + } +} + +func (p *Postgres) GetDocument(ctx context.Context, id string) (*Document, error) { + d, err := scanDocument(p.pool.QueryRow(ctx, documentSelect+`WHERE id = $1::uuid`, id)) + if isInvalidUUID(err) { + return nil, ErrNotFound + } + return d, err +} + +func (p *Postgres) ListDocuments(ctx context.Context, tenantID string, publishedOnly bool) ([]Document, error) { + q := documentSelect + `WHERE tenant_id = $1::uuid` + if publishedOnly { + q += ` AND status = 'published'` + } + rows, err := p.pool.Query(ctx, q+` ORDER BY created_at DESC, id DESC`, tenantID) + if isInvalidUUID(err) { + return []Document{}, nil + } + if err != nil { + return nil, err + } + defer rows.Close() + out := []Document{} + for rows.Next() { + d, err := scanDocument(rows) + if err != nil { + return nil, err + } + out = append(out, *d) + } + return out, rows.Err() +} + +func (p *Postgres) PublishDocument(ctx context.Context, id, by string, at time.Time) (*Document, error) { + // An already published document is returned unchanged. + _, err := p.pool.Exec(ctx, ` + UPDATE documents SET status = 'published', published_by = $2, published_at = $3, updated_at = $3 + WHERE id = $1::uuid AND status <> 'published'`, id, by, at.UTC()) + if isInvalidUUID(err) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + return p.GetDocument(ctx, id) +} + +func (p *Postgres) DeleteDocument(ctx context.Context, id string) error { + tag, err := p.pool.Exec(ctx, `DELETE FROM documents WHERE id = $1::uuid`, id) + if isInvalidUUID(err) { + return ErrNotFound + } + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + return nil +} diff --git a/internal/store/store.go b/internal/store/store.go index a486b58..01ce311 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -127,6 +127,14 @@ type Store interface { // SetLicenceLLMKey records (or clears, with "") the LiteLLM key id. SetLicenceLLMKey(ctx context.Context, id string, keyID string) error + // Documents (0008). ID and ObjectKey are chosen by the caller (the object + // is stored before the row). ListDocuments with publishedOnly hides drafts. + CreateDocument(ctx context.Context, d Document) (*Document, error) + GetDocument(ctx context.Context, id string) (*Document, error) + ListDocuments(ctx context.Context, tenantID string, publishedOnly bool) ([]Document, error) + PublishDocument(ctx context.Context, id, by string, at time.Time) (*Document, error) + DeleteDocument(ctx context.Context, id string) error + // Lifecycle Close() Ping(ctx context.Context) error diff --git a/internal/store/types.go b/internal/store/types.go index 68c2a57..f30a568 100644 --- a/internal/store/types.go +++ b/internal/store/types.go @@ -245,3 +245,28 @@ type Licence struct { // Werkpilot licence (D6); the handle for /key/delete. Never the secret. LLMKeyID string `json:"llm_key_id,omitempty"` } + +// Document — a file BreakPilot hands to a tenant (migration 0008). Staff +// upload it as a draft; tenants see it once it is published. +type Document struct { + ID string `json:"id"` + TenantID string `json:"tenant_id"` + Title string `json:"title"` + Description string `json:"description"` + Filename string `json:"filename"` + ContentType string `json:"content_type"` + SizeBytes int64 `json:"size_bytes"` + SHA256 string `json:"sha256"` + ObjectKey string `json:"-"` + Status string `json:"status"` // draft | published + UploadedBy string `json:"uploaded_by,omitempty"` + PublishedBy string `json:"published_by,omitempty"` + PublishedAt *time.Time `json:"published_at,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +const ( + DocumentDraft = "draft" + DocumentPublished = "published" +) diff --git a/migrations/0008_documents.down.sql b/migrations/0008_documents.down.sql new file mode 100644 index 0000000..a416e81 --- /dev/null +++ b/migrations/0008_documents.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS documents; diff --git a/migrations/0008_documents.up.sql b/migrations/0008_documents.up.sql new file mode 100644 index 0000000..9db7b54 --- /dev/null +++ b/migrations/0008_documents.up.sql @@ -0,0 +1,23 @@ +-- F2 (go-live 2026-09): documents BreakPilot hands to a tenant (conformity +-- documents, reports) until breakpilot-compliance delivers them itself. Staff +-- upload a draft, publish it, and only then does the tenant see it. The file +-- lives in object storage under object_key; this row is its index. +CREATE TABLE documents ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + title TEXT NOT NULL CHECK (char_length(title) BETWEEN 1 AND 200), + description TEXT NOT NULL DEFAULT '' CHECK (char_length(description) <= 2000), + filename TEXT NOT NULL, + content_type TEXT NOT NULL, + size_bytes BIGINT NOT NULL CHECK (size_bytes >= 0), + sha256 TEXT NOT NULL, + object_key TEXT NOT NULL UNIQUE, + status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published')), + uploaded_by TEXT NOT NULL DEFAULT '', + published_by TEXT, + published_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX documents_tenant_created ON documents (tenant_id, created_at DESC); diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index 8563d5c..1385ee4 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -114,8 +114,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) { } } - // Column assertions for later migrations (0007: licences.llm_key_id). - for _, c := range [][2]string{{"licences", "llm_key_id"}} { + // Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents). + for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}} { var exists bool err := db.QueryRow( "SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)", diff --git a/openapi.yaml b/openapi.yaml index 4b8e7c1..d7fc0b6 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -206,6 +206,20 @@ paths: application/json: { schema: { $ref: "#/components/schemas/Tenant" } } "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/documents: + get: + summary: A tenant's published documents. + description: Served by the same `{id}/{sub}` route as members; user tokens reach their own tenant only. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: Published documents, newest first. + content: + application/json: + schema: { type: object, properties: { items: { type: array, items: { $ref: "#/components/schemas/Document" } } } } + "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/members: get: summary: List the tenant's Keycloak organization members. @@ -400,6 +414,93 @@ paths: "200": { description: One page of audit entries. } "400": { $ref: "#/components/responses/BadRequest" } + /v1/admin/tenants/{id}/documents: + get: + summary: A tenant's documents, drafts included (staff). + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The documents, newest first. + content: + application/json: + schema: { type: object, properties: { items: { type: array, items: { $ref: "#/components/schemas/Document" } } } } + "404": { $ref: "#/components/responses/NotFound" } + post: + summary: Upload a document as a draft (staff). + description: | + multipart/form-data with optional `title` and `description` fields + before the `file` part. The file is streamed to object storage (limit + DOCUMENTS_MAX_MB, default 200). Allowed: pdf, zip, docx, xlsx, pptx, + png, jpg, txt, csv, json, xml. The title defaults to the file name. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + required: [file] + properties: + title: { type: string, maxLength: 200 } + description: { type: string, maxLength: 2000 } + file: { type: string, format: binary } + responses: + "201": + description: Stored as a draft. + content: + application/json: { schema: { $ref: "#/components/schemas/Document" } } + "400": { $ref: "#/components/responses/BadRequest" } + "404": { $ref: "#/components/responses/NotFound" } + "413": { description: Larger than the upload limit. } + "415": { description: File type not allowed. } + "503": { description: Document storage not configured. } + + /v1/admin/documents/{doc}/publish: + post: + summary: Publish a draft so the tenant sees it (staff). Idempotent. + parameters: + - { in: path, name: doc, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The published document. + content: + application/json: { schema: { $ref: "#/components/schemas/Document" } } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/admin/documents/{doc}: + delete: + summary: Delete a document and its file (staff). + parameters: + - { in: path, name: doc, required: true, schema: { type: string, format: uuid } } + responses: + "204": { description: Deleted. } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/tenants/{id}/documents/{doc}/download: + get: + summary: A five-minute download link for a published document. + description: | + User tokens only reach their own tenant. A service client may name the + downloading person in `X-Portal-User-Email` for the audit log. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: doc, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The link. + content: + application/json: + schema: + type: object + properties: + url: { type: string } + filename: { type: string } + content_type: { type: string } + expires_at: { type: string, format: date-time } + "404": { $ref: "#/components/responses/NotFound" } + /v1/entitlements: get: summary: List product entitlements for a tenant. @@ -1105,6 +1206,22 @@ components: error: { type: string, example: invalid_input } message: { type: string } + Document: + type: object + properties: + id: { type: string, format: uuid } + tenant_id: { type: string, format: uuid } + title: { type: string } + description: { type: string } + filename: { type: string } + content_type: { type: string } + size_bytes: { type: integer } + sha256: { type: string } + status: { type: string, enum: [draft, published] } + uploaded_by: { type: string } + published_by: { type: string } + published_at: { type: string, format: date-time } + created_at: { type: string, format: date-time } TenantActivity: type: object properties: -- 2.54.1