Harden control-plane membership, audit actor, and audit event bounds

Propagate account member removals, demotions, promotions, and
re-additions into every workspace organization record so removed or
demoted members lose workspace authority immediately while restored
members regain workspace access cleanly.

Restrict tenant-bound magic-link owner seeding to accounts with no
existing members so stored checkout contact email cannot restore a
removed member. Read control-plane audit actor IDs only from
authenticated request context instead of client-controlled headers.

Bound audit event text fields before queuing, signing, and storage in
pkg/audit so oversized request fields cannot cause memory exhaustion
during audit exports.

Contract-Neutral: Security hardening for control-plane membership sync, audit actor attribution, and audit event size bounds without public API contract changes
This commit is contained in:
rcourtman
2026-11-24 10:31:28 +00:00
parent d9c5f665d1
commit 70f3b0a3b3
22 changed files with 1550 additions and 60 deletions
@@ -19,6 +19,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/api"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/account"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/auditlog"
cpDocker "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/docker"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/entitlements"
cphandoff "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/handoff"
@@ -454,7 +455,9 @@ func (rt *providerMSPProofRuntime) createProviderMSPProofWorkspace(ctx context.C
}
path := "/api/accounts/" + url.PathEscape(accountID) + "/tenants"
req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(payload))
req = req.WithContext(ctx)
// No middleware runs in front of this in-process call; keep its audit
// events attributed to the operator.
req = req.WithContext(auditlog.WithActor(ctx, auditlog.ActorAdminKey))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-User-Email", ownerEmail)
rec := httptest.NewRecorder()
+6
View File
@@ -57,6 +57,12 @@ Each event includes:
- **Details** (human-readable description)
- **Cryptographic signature** (tamper detection)
Text fields are stored with a size limit: 64 bytes for the event type and the
client IP, 512 bytes for the user and the request path, and 1,024 bytes for the
details. Longer text is cut to fit and ends in `...[truncated]`. The signature
covers the text as stored. Events recorded before this limit existed are kept
as they are.
---
## Viewing Audit Events
@@ -1134,6 +1134,12 @@ responsive shell appear to ignore an operator.
control-plane registry cannot resolve a stable account `User.ID`; it must
not sign a tenant handoff with a blank subject and let the tenant runtime
promote contact email into identity.
Control-plane magic-link verification may seed an owner membership only on
an account that has no members yet. Once an account has members, a
tenant-bound link, tenant- or portal-targeted, must fail closed with `403`
for an email that is not a current member: stored tenant contact email must
not restore a removed member, and access returns only through an accepted
invitation.
That same portal boundary also owns the signed-in shell shape: hosted
arrivals default to `Workspaces`, self-hosted-only arrivals default to
`Billing`, and the shell destinations are limited to `Workspaces`,
@@ -4467,9 +4473,44 @@ generated-report purge) are removed, so nothing deletes history or reports
because a plan ended. Plan copy, the billing summary and the comparison table
no longer list history as a paid line. Continuing subscribers lose nothing.
### Top-level Availability page and inline management (24 November 2026)
`frontend-modern/src/App.tsx` and `frontend-modern/src/AppLayout.tsx` expose
the primary `/availability` route when `PlatformAdmission.Availability` is true.
Cloud, licensing, and paid feature entitlement boundaries are unchanged.
### Account membership changes reach existing workspaces
A hosted workspace authorizes every request against its own organization
metadata, seeded from the account's members at provisioning, and its sessions
carry no account fact. Deleting or lowering an account membership in the
registry alone stops new handoffs but leaves an open workspace session with the
earlier role. `internal/cloudcp/account/handlers.go` carries removals,
demotions, promotions and re-additions into every workspace of the account
through `internal/cloudcp/stripe/workspace_access.go`.
Removal drops the member and any pending workspace invitation, matched by the
stable user ID or by a legacy email-keyed record the handoff would still admit.
A lowered account role caps the stored workspace role at the shared
account-role-to-organization-role mapping. A raised account role or a
re-added existing member is synced into every existing workspace with at least
the mapped organization role, preserving any higher workspace-local grant so
undoing a demotion or re-inviting a removed member restores workspace access.
A workspace owned by a removed or demoted member passes to the account's
longest-standing other owner, the same deterministic fallback provisioning uses.
An open workspace session is held to the rewritten membership from its next
request, as after a change made inside the workspace. The session record, API
tokens minted in the workspace and session lifetime are unchanged.
The workspace write uses the organization's optimistic save, reloads and
reapplies when the running workspace wrote in between, and restores runtime
file ownership. Every workspace is attempted. If one cannot be updated the
request fails and the account membership stays as it was, so the change can be
repeated. The write takes no runtime lifecycle lease: a rollout, health check
or recovery hold on one workspace must not keep access in place elsewhere. A
rollout that restores its snapshot can bring an earlier member list back and is
not reconciled here. Pending account invitations have opened no workspace and
are not carried. Routes, request fields and account roles are unchanged.
Registered account-handler, route and Stripe provisioner tests cover ordering,
failure retention, ownership succession, two-way restoration, legacy records,
the registered wiring and the boundary to other accounts.
@@ -57,6 +57,12 @@ Each event includes:
- **Details** (human-readable description)
- **Cryptographic signature** (tamper detection)
Text fields are stored with a size limit: 64 bytes for the event type and the
client IP, 512 bytes for the user and the request path, and 1,024 bytes for the
details. Longer text is cut to fit and ends in `...[truncated]`. The signature
covers the text as stored. Events recorded before this limit existed are kept
as they are.
---
## Viewing Audit Events
+1 -6
View File
@@ -14,15 +14,10 @@ func auditEvent(r *http.Request, eventName, outcome string) *zerolog.Event {
e = log.Warn()
}
actorID := auditlog.ActorID(r)
if actorID == "" {
actorID = "admin_key"
}
return e.
Str("audit_event", eventName).
Str("outcome", outcome).
Str("actor_id", actorID).
Str("actor_id", auditlog.ActorID(r)).
Str("client_ip", auditlog.ClientIP(r)).
Str("method", r.Method).
Str("path", auditlog.RequestPath(r))
+85 -3
View File
@@ -1,6 +1,7 @@
package account
import (
"context"
"encoding/json"
"fmt"
"io"
@@ -9,9 +10,37 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rs/zerolog/log"
)
// WorkspaceAccessLimiter carries account membership changes into the account's
// workspaces, which authorize requests against their own member list rather
// than the registry. Implemented by internal/cloudcp/stripe.Provisioner.
type WorkspaceAccessLimiter interface {
RevokeWorkspaceAccess(ctx context.Context, accountID, userID string) error
LowerWorkspaceAccess(ctx context.Context, accountID, userID string, role registry.MemberRole) error
SyncWorkspaceAccess(ctx context.Context, accountID, userID string, role registry.MemberRole) error
}
// memberRoleLowered reports whether an account role change takes workspace
// authority away from the member.
func memberRoleLowered(from, to registry.MemberRole) bool {
return !models.OrganizationRoleAtLeast(
models.OrganizationRoleFromAccountRole(string(to)),
models.OrganizationRoleFromAccountRole(string(from)),
)
}
// memberRoleRaised reports whether an account role change grants higher
// workspace authority than the member previously held.
func memberRoleRaised(from, to registry.MemberRole) bool {
return !models.OrganizationRoleAtLeast(
models.OrganizationRoleFromAccountRole(string(from)),
models.OrganizationRoleFromAccountRole(string(to)),
)
}
type accessSubjectResponse struct {
SubjectID string `json:"subject_id"`
UserID string `json:"user_id,omitempty"`
@@ -135,7 +164,7 @@ func loadAccountAccessTarget(reg *registry.TenantRegistry, accountID string, sub
}
// HandleInviteMember returns an authenticated handler that invites a user to an account.
func HandleInviteMember(reg *registry.TenantRegistry) http.HandlerFunc {
func HandleInviteMember(reg *registry.TenantRegistry, workspaces ...WorkspaceAccessLimiter) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
@@ -308,6 +337,24 @@ func HandleInviteMember(reg *registry.TenantRegistry) http.HandlerFunc {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
// Keep existing workspaces aligned so a re-invited member can enter
// workspaces they were previously removed from. Roll back on failure so
// the invite can be retried cleanly.
if len(workspaces) > 0 && workspaces[0] != nil {
if err := workspaces[0].SyncWorkspaceAccess(r.Context(), accountID, u.ID, role); err != nil {
_ = reg.DeleteMembership(accountID, u.ID)
auditEvent(r, "cp_account_member_invite", "failure").
Err(err).
Str("account_id", accountID).
Str("user_id", u.ID).
Str("email", email).
Str("role", string(role)).
Str("reason", "workspace_access_sync_failed").
Msg("Account member invite failed")
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
}
if err := reg.DeleteInvitationByAccountAndEmail(accountID, email); err != nil {
auditEvent(r, "cp_account_member_invite", "failure").
Err(err).
@@ -343,7 +390,7 @@ type updateMemberRoleRequest struct {
}
// HandleUpdateMemberRole returns an authenticated handler that updates a member's role.
func HandleUpdateMemberRole(reg *registry.TenantRegistry) http.HandlerFunc {
func HandleUpdateMemberRole(reg *registry.TenantRegistry, workspaces ...WorkspaceAccessLimiter) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPatch {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
@@ -488,6 +535,26 @@ func HandleUpdateMemberRole(reg *registry.TenantRegistry) http.HandlerFunc {
}
if target.membership != nil {
// Workspaces first: if the registry write then fails, the change can
// be retried without leaving workspaces out of sync.
if len(workspaces) > 0 && workspaces[0] != nil {
var syncErr error
if memberRoleLowered(currentRole, role) {
syncErr = workspaces[0].LowerWorkspaceAccess(r.Context(), accountID, userID, role)
} else if memberRoleRaised(currentRole, role) {
syncErr = workspaces[0].SyncWorkspaceAccess(r.Context(), accountID, userID, role)
}
if syncErr != nil {
auditEvent(r, "cp_account_member_role_update", "failure").
Err(syncErr).
Str("account_id", accountID).
Str("user_id", userID).
Str("reason", "workspace_access_update_failed").
Msg("Account member role update failed")
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
}
if err := reg.UpdateMembershipRole(accountID, userID, role); err != nil {
if isNotFoundErr(err) {
auditEvent(r, "cp_account_member_role_update", "failure").
@@ -543,7 +610,7 @@ func HandleUpdateMemberRole(reg *registry.TenantRegistry) http.HandlerFunc {
}
// HandleRemoveMember returns an authenticated handler that removes a user from an account.
func HandleRemoveMember(reg *registry.TenantRegistry) http.HandlerFunc {
func HandleRemoveMember(reg *registry.TenantRegistry, workspaces ...WorkspaceAccessLimiter) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
@@ -667,6 +734,21 @@ func HandleRemoveMember(reg *registry.TenantRegistry) http.HandlerFunc {
}
if target.membership != nil {
// Workspaces first: the membership is what makes a failed removal
// retryable, and a member already gone from a workspace cannot
// hand off into it again.
if len(workspaces) > 0 && workspaces[0] != nil {
if err := workspaces[0].RevokeWorkspaceAccess(r.Context(), accountID, userID); err != nil {
auditEvent(r, "cp_account_member_remove", "failure").
Err(err).
Str("account_id", accountID).
Str("user_id", userID).
Str("reason", "workspace_access_revoke_failed").
Msg("Account member removal failed")
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
}
if err := reg.DeleteMembership(accountID, userID); err != nil {
if isNotFoundErr(err) {
auditEvent(r, "cp_account_member_remove", "failure").
+148
View File
@@ -2,10 +2,14 @@ package account
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"sort"
"strings"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/admin"
@@ -631,3 +635,147 @@ func TestRemoveMember_ForbiddenWhenActorRoleMissing(t *testing.T) {
t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusForbidden, rec.Body.String())
}
}
type fakeWorkspaceAccessLimiter struct {
reg *registry.TenantRegistry
err error
revoked []string
lowered []string
synced []string
}
func (f *fakeWorkspaceAccessLimiter) RevokeWorkspaceAccess(_ context.Context, accountID, userID string) error {
// The membership is still there: workspaces are updated first.
if m, err := f.reg.GetMembership(accountID, userID); err != nil || m == nil {
return fmt.Errorf("membership of %s already removed (err=%v)", userID, err)
}
f.revoked = append(f.revoked, userID)
return f.err
}
func (f *fakeWorkspaceAccessLimiter) LowerWorkspaceAccess(_ context.Context, _, userID string, role registry.MemberRole) error {
f.lowered = append(f.lowered, userID+"="+string(role))
return f.err
}
func (f *fakeWorkspaceAccessLimiter) SyncWorkspaceAccess(_ context.Context, _, userID string, role registry.MemberRole) error {
f.synced = append(f.synced, userID+"="+string(role))
return f.err
}
func TestMemberRemovalAndDemotionAreCarriedIntoWorkspaces(t *testing.T) {
reg := newTestRegistry(t)
const accountID = "a-workspaces"
if err := reg.CreateAccount(&registry.Account{ID: accountID, Kind: registry.AccountKindMSP, DisplayName: "Test"}); err != nil {
t.Fatal(err)
}
for userID, role := range map[string]registry.MemberRole{"u_owner": registry.MemberRoleOwner, "u_admin": registry.MemberRoleAdmin} {
if err := reg.CreateUser(&registry.User{ID: userID, Email: userID + "@msp.com"}); err != nil {
t.Fatal(err)
}
if err := reg.CreateMembership(&registry.AccountMembership{AccountID: accountID, UserID: userID, Role: role}); err != nil {
t.Fatal(err)
}
}
if err := reg.UpsertInvitation(&registry.AccountInvitation{ID: "inv_pending", AccountID: accountID, Email: "pending@msp.com", Role: registry.MemberRoleAdmin}); err != nil {
t.Fatal(err)
}
pending, err := reg.ListInvitationsByAccount(accountID)
if err != nil || len(pending) != 1 {
t.Fatalf("ListInvitationsByAccount = %v, %v", pending, err)
}
workspaces := &fakeWorkspaceAccessLimiter{reg: reg}
mux := http.NewServeMux()
mux.Handle("POST /api/accounts/{account_id}/members", HandleInviteMember(reg, workspaces))
mux.Handle("PATCH /api/accounts/{account_id}/members/{user_id}", HandleUpdateMemberRole(reg, workspaces))
mux.Handle("DELETE /api/accounts/{account_id}/members/{user_id}", HandleRemoveMember(reg, workspaces))
do := func(method, subjectID, body string) int {
t.Helper()
path := "/api/accounts/" + accountID + "/members"
if subjectID != "" {
path += "/" + subjectID
}
req := httptest.NewRequest(method, path, bytes.NewBufferString(body))
req.Header.Set("X-User-Role", string(registry.MemberRoleOwner))
return doRawRequest(t, mux, req).Code
}
role := func() registry.MemberRole {
t.Helper()
m, err := reg.GetMembership(accountID, "u_admin")
if err != nil || m == nil {
t.Fatalf("GetMembership = %v, %v", m, err)
}
return m.Role
}
// A pending invitation has opened no workspace.
if code := do(http.MethodDelete, pending[0].ID, ""); code != http.StatusNoContent {
t.Fatalf("remove invitation: status = %d", code)
}
if len(workspaces.revoked) != 0 || len(workspaces.lowered) != 0 || len(workspaces.synced) != 0 {
t.Fatalf("workspaces touched for pending invitation: revoked=%v lowered=%v synced=%v", workspaces.revoked, workspaces.lowered, workspaces.synced)
}
// A promotion syncs the higher role into existing workspaces.
if code := do(http.MethodPatch, "u_admin", `{"role":"owner"}`); code != http.StatusOK {
t.Fatalf("promote: status = %d", code)
}
if got, want := strings.Join(workspaces.synced, ","), "u_admin=owner"; got != want {
t.Fatalf("synced after promote = %q, want %q", got, want)
}
if len(workspaces.revoked) != 0 || len(workspaces.lowered) != 0 {
t.Fatalf("workspaces revoked/lowered on promotion: revoked=%v lowered=%v", workspaces.revoked, workspaces.lowered)
}
// A workspace that cannot be updated keeps the account as it was.
workspaces.err = errors.New("workspace unavailable")
if code := do(http.MethodPatch, "u_admin", `{"role":"tech"}`); code != http.StatusInternalServerError {
t.Fatalf("demote with failing workspaces: status = %d", code)
}
if got := role(); got != registry.MemberRoleOwner {
t.Fatalf("role after failed demotion = %q", got)
}
if code := do(http.MethodDelete, "u_admin", ""); code != http.StatusInternalServerError {
t.Fatalf("remove with failing workspaces: status = %d", code)
}
role()
workspaces.err = nil
if code := do(http.MethodPatch, "u_admin", `{"role":"tech"}`); code != http.StatusOK {
t.Fatalf("demote: status = %d", code)
}
if got := role(); got != registry.MemberRoleTech {
t.Fatalf("role after demotion = %q", got)
}
if code := do(http.MethodDelete, "u_admin", ""); code != http.StatusNoContent {
t.Fatalf("remove: status = %d", code)
}
if m, err := reg.GetMembership(accountID, "u_admin"); err != nil || m != nil {
t.Fatalf("membership after removal = %v, %v", m, err)
}
// Re-inviting a removed user fails atomically if workspace sync fails, and
// syncs into existing workspaces when it succeeds.
workspaces.err = errors.New("workspace unavailable")
if code := do(http.MethodPost, "", `{"email":"u_admin@msp.com","role":"admin"}`); code != http.StatusInternalServerError {
t.Fatalf("re-invite with failing workspaces: status = %d", code)
}
if m, err := reg.GetMembership(accountID, "u_admin"); err != nil || m != nil {
t.Fatalf("membership should be rolled back on failed workspace sync = %v, %v", m, err)
}
workspaces.err = nil
if code := do(http.MethodPost, "", `{"email":"u_admin@msp.com","role":"admin"}`); code != http.StatusCreated {
t.Fatalf("re-invite: status = %d", code)
}
if got := role(); got != registry.MemberRoleAdmin {
t.Fatalf("role after re-invite = %q", got)
}
if got, want := strings.Join(workspaces.lowered, ","), "u_admin=tech,u_admin=tech"; got != want {
t.Fatalf("lowered = %q, want %q", got, want)
}
if got, want := strings.Join(workspaces.revoked, ","), "u_admin,u_admin"; got != want {
t.Fatalf("revoked = %q, want %q", got, want)
}
if got, want := strings.Join(workspaces.synced, ","), "u_admin=owner,u_admin=admin,u_admin=admin"; got != want {
t.Fatalf("synced = %q, want %q", got, want)
}
}
+1 -1
View File
@@ -88,7 +88,7 @@ func AdminKeyMiddleware(adminKey string, next http.Handler) http.Handler {
// Admin-key authenticated requests bypass session/membership middleware.
// Provide a conservative default role so downstream account-mutation auth
// checks stay fail-closed on missing role context.
req := r.Clone(r.Context())
req := r.Clone(auditlog.WithActor(r.Context(), auditlog.ActorAdminKey))
req.Header.Set("X-User-Role", string(registry.MemberRoleOwner))
next.ServeHTTP(w, req)
})
+24 -8
View File
@@ -1,6 +1,7 @@
package auditlog
import (
"context"
"net/http"
"strings"
@@ -12,18 +13,33 @@ func ClientIP(r *http.Request) string {
return proxytrust.ClientIP(r)
}
// ActorID returns the request actor identifier from common headers.
const (
// ActorAdminKey is the audit actor for admin-key authenticated requests.
ActorAdminKey = "admin_key"
// ActorAnonymous is the audit actor for requests nothing authenticated.
ActorAnonymous = "anonymous"
)
// actorKey is the context key for the authenticated audit actor.
type actorKey struct{}
// WithActor returns a copy of ctx carrying the actor that authentication
// middleware verified for the request.
func WithActor(ctx context.Context, actorID string) context.Context {
return context.WithValue(ctx, actorKey{}, strings.TrimSpace(actorID))
}
// ActorID returns the actor that authentication middleware verified for the
// request, or ActorAnonymous when nothing authenticated it. Request headers
// are client-controlled and are never consulted.
func ActorID(r *http.Request) string {
if r == nil {
return ""
return ActorAnonymous
}
for _, header := range []string{"X-Actor-ID", "X-Actor-Id", "X-User-ID", "X-User-Id"} {
if v := strings.TrimSpace(r.Header.Get(header)); v != "" {
return v
}
if v, ok := r.Context().Value(actorKey{}).(string); ok && v != "" {
return v
}
return ""
return ActorAnonymous
}
// RequestPath returns a stable request path for audit metadata.
+34 -30
View File
@@ -85,6 +85,10 @@ func TestClientIP(t *testing.T) {
}
func TestActorID(t *testing.T) {
withActor := func(r *http.Request, actorID string) *http.Request {
return r.WithContext(WithActor(r.Context(), actorID))
}
tests := []struct {
name string
request *http.Request
@@ -93,47 +97,47 @@ func TestActorID(t *testing.T) {
{
name: "nil request",
request: nil,
expectedID: "",
expectedID: ActorAnonymous,
},
{
name: "X-Actor-ID header",
request: newRequestWithHeaders(t, "", map[string]string{"X-Actor-ID": "user-123"}),
name: "no authenticated actor",
request: newRequestWithHeaders(t, "", nil),
expectedID: ActorAnonymous,
},
{
name: "authenticated actor from context",
request: withActor(newRequestWithHeaders(t, "", nil), "user-123"),
expectedID: "user-123",
},
{
name: "X-Actor-Id header (mixed case)",
request: newRequestWithHeaders(t, "", map[string]string{"X-Actor-Id": "user-456"}),
name: "admin key actor from context",
request: withActor(newRequestWithHeaders(t, "", nil), ActorAdminKey),
expectedID: ActorAdminKey,
},
{
name: "authenticated actor is trimmed",
request: withActor(newRequestWithHeaders(t, "", nil), " user-456 "),
expectedID: "user-456",
},
{
name: "X-User-ID fallback",
name: "whitespace-only actor is anonymous",
request: withActor(newRequestWithHeaders(t, "", nil), " "),
expectedID: ActorAnonymous,
},
{
name: "X-Actor-ID header is ignored",
request: newRequestWithHeaders(t, "", map[string]string{"X-Actor-ID": "actor-1"}),
expectedID: ActorAnonymous,
},
{
name: "X-User-ID header is ignored",
request: newRequestWithHeaders(t, "", map[string]string{"X-User-ID": "user-789"}),
expectedID: "user-789",
expectedID: ActorAnonymous,
},
{
name: "X-User-Id fallback",
request: newRequestWithHeaders(t, "", map[string]string{"X-User-Id": "user-abc"}),
expectedID: "user-abc",
},
{
name: "X-Actor-ID takes precedence over X-User-ID",
request: newRequestWithHeaders(t, "", map[string]string{"X-Actor-ID": "actor-1", "X-User-ID": "user-1"}),
expectedID: "actor-1",
},
{
name: "whitespace-only returns empty",
request: newRequestWithHeaders(t, "", map[string]string{"X-Actor-ID": " "}),
expectedID: "",
},
{
name: "no matching headers",
request: newRequestWithHeaders(t, "", map[string]string{"Accept": "application/json"}),
expectedID: "",
},
{
name: "empty headers",
request: newRequestWithHeaders(t, "", nil),
expectedID: "",
name: "client headers do not override authenticated actor",
request: withActor(newRequestWithHeaders(t, "", map[string]string{"X-Actor-ID": "actor-1", "X-User-ID": "user-1"}), "user-123"),
expectedID: "user-123",
},
}
+36 -6
View File
@@ -2,6 +2,7 @@ package auth
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
@@ -19,6 +20,10 @@ import (
const handoffTTL = 60 * time.Second
// errAccountMembershipRequired is returned when a sign-in link is bound to an
// account that already has members and the link's email is not one of them.
var errAccountMembershipRequired = errors.New("account membership required")
type adminGenerateMagicLinkRequest struct {
Email string `json:"email"`
TenantID string `json:"tenant_id"`
@@ -77,6 +82,15 @@ func HandleMagicLinkVerify(svc *Service, reg *registry.TenantRegistry, tenantsDi
redirectPath = "/portal"
}
userID, err := ensurePortalUserAndMembership(reg, token.TenantID, token.Email)
if errors.Is(err, errAccountMembershipRequired) {
auditEvent(r, "cp_magic_link_verify", "failure").
Str("tenant_id", token.TenantID).
Str("email", token.Email).
Str("reason", "account_membership_required").
Msg("Magic link verification failed")
writeError(w, http.StatusForbidden, "forbidden", "Account membership required")
return
}
if err != nil {
auditEvent(r, "cp_magic_link_verify", "failure").
Err(err).
@@ -152,6 +166,15 @@ func HandleMagicLinkVerify(svc *Service, reg *registry.TenantRegistry, tenantsDi
}
userID, err := ensureAccountUserAndMembership(reg, tenant, token.Email)
if errors.Is(err, errAccountMembershipRequired) {
auditEvent(r, "cp_magic_link_verify", "failure").
Str("tenant_id", tenant.ID).
Str("email", token.Email).
Str("reason", "account_membership_required").
Msg("Magic link verification failed")
writeError(w, http.StatusForbidden, "forbidden", "Account membership required")
return
}
trimmedUserID := strings.TrimSpace(userID)
if err != nil || trimmedUserID == "" || strings.Contains(trimmedUserID, "@") {
auditEvent(r, "cp_magic_link_verify", "failure").
@@ -361,15 +384,10 @@ func auditEvent(r *http.Request, eventName, outcome string) *zerolog.Event {
e = log.Warn()
}
actorID := auditlog.ActorID(r)
if actorID == "" {
actorID = "admin_key"
}
return e.
Str("audit_event", eventName).
Str("outcome", outcome).
Str("actor_id", actorID).
Str("actor_id", auditlog.ActorID(r)).
Str("client_ip", auditlog.ClientIP(r)).
Str("method", r.Method).
Str("path", auditlog.RequestPath(r))
@@ -493,6 +511,18 @@ func ensureAccountUserAndMembership(reg *registry.TenantRegistry, tenant *regist
return "", fmt.Errorf("lookup membership: %w", err)
}
if m == nil {
// A sign-in link proves control of a mailbox, not authority over the
// account. It may seed the first owner of an account nobody belongs to
// yet; once the account has members, access comes only from an accepted
// invitation, so a link mailed to stored contact email cannot undo a
// member's removal.
members, listErr := reg.ListMembersByAccount(accountID)
if listErr != nil {
return "", fmt.Errorf("list account members: %w", listErr)
}
if len(members) > 0 {
return "", errAccountMembershipRequired
}
newMembership := &registry.AccountMembership{
AccountID: accountID,
UserID: user.ID,
@@ -382,3 +382,126 @@ func TestHandleMagicLinkVerifyTenantTargetRejectsEmailShapedRegistryUserID(t *te
t.Fatalf("membership = %+v, want nil", membership)
}
}
func TestHandleMagicLinkVerifyDoesNotRestoreRemovedAccountMember(t *testing.T) {
dir := t.TempDir()
reg, err := registry.NewTenantRegistry(dir)
if err != nil {
t.Fatalf("NewTenantRegistry: %v", err)
}
t.Cleanup(func() { _ = reg.Close() })
accountID, err := registry.GenerateAccountID()
if err != nil {
t.Fatalf("GenerateAccountID: %v", err)
}
if err := reg.CreateAccount(&registry.Account{
ID: accountID,
Kind: registry.AccountKindIndividual,
DisplayName: "Hosted Account",
}); err != nil {
t.Fatalf("CreateAccount: %v", err)
}
// The workspace keeps the checkout contact email of the member who bought it.
if err := reg.Create(&registry.Tenant{
ID: "t-tenant-removed",
AccountID: accountID,
Email: "buyer@example.com",
DisplayName: "Hosted Workspace",
State: registry.TenantStateActive,
}); err != nil {
t.Fatalf("Create tenant: %v", err)
}
for _, user := range []*registry.User{
{ID: "u_buyer", Email: "buyer@example.com"},
{ID: "u_owner", Email: "owner@example.com"},
} {
if err := reg.CreateUser(user); err != nil {
t.Fatalf("CreateUser(%s): %v", user.ID, err)
}
if err := reg.CreateMembership(&registry.AccountMembership{
AccountID: accountID,
UserID: user.ID,
Role: registry.MemberRoleOwner,
}); err != nil {
t.Fatalf("CreateMembership(%s): %v", user.ID, err)
}
}
tenantsDir := filepath.Join(dir, "tenants")
tenantDir := filepath.Join(tenantsDir, "t-tenant-removed")
if err := os.MkdirAll(tenantDir, 0o700); err != nil {
t.Fatalf("MkdirAll tenant dir: %v", err)
}
handoffKey, err := cloudauth.GenerateHandoffKey()
if err != nil {
t.Fatalf("GenerateHandoffKey: %v", err)
}
if err := os.WriteFile(filepath.Join(tenantDir, cloudauth.HandoffKeyFile), handoffKey, 0o600); err != nil {
t.Fatalf("WriteFile handoff key: %v", err)
}
svc, err := NewService(dir)
if err != nil {
t.Fatalf("NewService: %v", err)
}
t.Cleanup(svc.Close)
verify := func(t *testing.T, generate func(email, tenantID string) (string, error)) *httptest.ResponseRecorder {
t.Helper()
token, err := generate("buyer@example.com", "t-tenant-removed")
if err != nil {
t.Fatalf("generate magic link token: %v", err)
}
req := httptest.NewRequest(http.MethodGet, "/auth/magic-link/verify?token="+token, nil)
rec := httptest.NewRecorder()
HandleMagicLinkVerify(svc, reg, tenantsDir, "cloud.example.com", "/portal")(rec, req)
return rec
}
// While the buyer is still a member, the tenant-bound link signs them in.
if rec := verify(t, svc.GenerateToken); rec.Code != http.StatusTemporaryRedirect {
t.Fatalf("member status=%d body=%q", rec.Code, rec.Body.String())
}
if err := reg.DeleteMembership(accountID, "u_buyer"); err != nil {
t.Fatalf("DeleteMembership: %v", err)
}
for _, tc := range []struct {
name string
generate func(email, tenantID string) (string, error)
}{
{name: "tenant target", generate: svc.GenerateToken},
{name: "portal target", generate: svc.GeneratePortalToken},
} {
t.Run(tc.name, func(t *testing.T) {
rec := verify(t, tc.generate)
if rec.Code != http.StatusForbidden {
t.Fatalf("status=%d, want %d body=%q", rec.Code, http.StatusForbidden, rec.Body.String())
}
if got := rec.Header().Get("Location"); got != "" {
t.Fatalf("location=%q, want no redirect", got)
}
if cookies := rec.Result().Cookies(); len(cookies) != 0 {
t.Fatalf("cookies=%#v, want no session", cookies)
}
membership, err := reg.GetMembership(accountID, "u_buyer")
if err != nil {
t.Fatalf("GetMembership: %v", err)
}
if membership != nil {
t.Fatalf("membership = %+v, want removed member to stay removed", membership)
}
})
}
members, err := reg.ListMembersByAccount(accountID)
if err != nil {
t.Fatalf("ListMembersByAccount: %v", err)
}
if len(members) != 1 || members[0].UserID != "u_owner" {
t.Fatalf("members = %+v, want only the remaining owner", members)
}
}
+2 -1
View File
@@ -5,6 +5,7 @@ import (
"net/http"
"strings"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/auditlog"
cpauth "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/auth"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
)
@@ -43,7 +44,7 @@ func requireSessionAuth(sessionSvc *cpauth.Service, reg *registry.TenantRegistry
return
}
req := r.Clone(r.Context())
req := r.Clone(auditlog.WithActor(r.Context(), claims.UserID))
req.Header.Set("X-User-ID", claims.UserID)
req.Header.Set("X-User-Email", claims.Email)
next.ServeHTTP(w, req)
+3 -3
View File
@@ -203,9 +203,9 @@ func RegisterRoutes(mux *http.ServeMux, deps *Deps) {
// Account membership (session + account-membership authenticated)
listMembers := account.HandleListMembers(deps.Registry)
inviteMember := account.HandleInviteMember(deps.Registry)
updateRole := account.HandleUpdateMemberRole(deps.Registry)
removeMember := account.HandleRemoveMember(deps.Registry)
inviteMember := account.HandleInviteMember(deps.Registry, provisioner)
updateRole := account.HandleUpdateMemberRole(deps.Registry, provisioner)
removeMember := account.HandleRemoveMember(deps.Registry, provisioner)
membersCollection := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
+160
View File
@@ -1,14 +1,19 @@
package cloudcp
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/auditlog"
cpauth "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/auth"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/portal"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func TestRegisterRoutes_StatusAuthModes(t *testing.T) {
@@ -244,6 +249,161 @@ func TestRegisterRoutes_LogoutRevokesSession(t *testing.T) {
}
}
func TestRegisterRoutes_AuditActorIgnoresClientHeaders(t *testing.T) {
dir := t.TempDir()
reg, err := registry.NewTenantRegistry(dir)
if err != nil {
t.Fatalf("NewTenantRegistry: %v", err)
}
t.Cleanup(func() { _ = reg.Close() })
accountID, err := registry.GenerateAccountID()
if err != nil {
t.Fatalf("GenerateAccountID: %v", err)
}
if err := reg.CreateAccount(&registry.Account{
ID: accountID,
Kind: registry.AccountKindMSP,
DisplayName: "Acme MSP",
}); err != nil {
t.Fatalf("CreateAccount: %v", err)
}
userID, err := registry.GenerateUserID()
if err != nil {
t.Fatalf("GenerateUserID: %v", err)
}
if err := reg.CreateUser(&registry.User{
ID: userID,
Email: "admin@example.com",
}); err != nil {
t.Fatalf("CreateUser: %v", err)
}
if err := reg.CreateMembership(&registry.AccountMembership{
AccountID: accountID,
UserID: userID,
Role: registry.MemberRoleAdmin,
}); err != nil {
t.Fatalf("CreateMembership: %v", err)
}
magicSvc, err := cpauth.NewService(dir)
if err != nil {
t.Fatalf("NewService: %v", err)
}
t.Cleanup(magicSvc.Close)
token, err := magicSvc.GenerateSessionToken(userID, "admin@example.com", cpauth.SessionTTL)
if err != nil {
t.Fatalf("GenerateSessionToken: %v", err)
}
mux := http.NewServeMux()
RegisterRoutes(mux, &Deps{
Config: &CPConfig{
DataDir: dir,
AdminKey: "test-admin-key",
BaseURL: "https://cloud.example.com",
StripeWebhookSecret: "whsec_test",
},
Registry: reg,
MagicLinks: magicSvc,
Version: "test",
})
tests := []struct {
name string
method string
path string
body string
headers map[string]string
auditEvent string
wantActor string
}{
{
name: "session request claiming another user",
method: http.MethodPost,
path: "/api/accounts/" + accountID + "/members",
body: `{"email":"tech@example.com","role":"tech"}`,
headers: map[string]string{
"Authorization": "Bearer " + token,
"X-Actor-ID": "u_SOMEONEELSE",
},
auditEvent: "cp_account_member_invite",
wantActor: userID,
},
{
name: "session request claiming the admin key",
method: http.MethodPost,
path: "/api/accounts/" + accountID + "/members",
body: `{"email":"viewer@example.com","role":"read_only"}`,
headers: map[string]string{
"Authorization": "Bearer " + token,
"X-Actor-ID": auditlog.ActorAdminKey,
},
auditEvent: "cp_account_member_invite",
wantActor: userID,
},
{
name: "unauthenticated magic link verification",
method: http.MethodGet,
path: "/auth/magic-link/verify?token=invalid",
headers: map[string]string{
"Accept": "application/json",
"X-Actor-ID": userID,
"X-User-ID": userID,
},
auditEvent: "cp_magic_link_verify",
wantActor: auditlog.ActorAnonymous,
},
{
name: "admin key request claiming a user",
method: http.MethodPost,
path: "/admin/magic-link",
body: `{}`,
headers: map[string]string{
"X-Admin-Key": "test-admin-key",
"X-Actor-ID": userID,
"X-User-ID": userID,
},
auditEvent: "cp_magic_link_admin_generate",
wantActor: auditlog.ActorAdminKey,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var audit bytes.Buffer
oldLogger := log.Logger
log.Logger = zerolog.New(&audit)
defer func() { log.Logger = oldLogger }()
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
for k, v := range tc.headers {
req.Header.Set(k, v)
}
mux.ServeHTTP(httptest.NewRecorder(), req)
actors := []string{}
for _, line := range strings.Split(audit.String(), "\n") {
var event map[string]any
if json.Unmarshal([]byte(line), &event) == nil && event["audit_event"] == tc.auditEvent {
actor, _ := event["actor_id"].(string)
actors = append(actors, actor)
}
}
if len(actors) == 0 {
t.Fatalf("no %s audit event in %q", tc.auditEvent, audit.String())
}
for _, actor := range actors {
if actor != tc.wantActor {
t.Fatalf("%s actor_id = %q, want %q", tc.auditEvent, actor, tc.wantActor)
}
}
})
}
}
func TestRegisterRoutes_PortalBootstrapRequiresSession(t *testing.T) {
dir := t.TempDir()
reg, err := registry.NewTenantRegistry(dir)
+95
View File
@@ -7,6 +7,7 @@ import (
"encoding/json"
cpauth "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/auth"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"net/http"
"net/http/httptest"
"path/filepath"
@@ -664,3 +665,97 @@ func TestRegisterRoutesResumeUsesConfiguredBillingMode(t *testing.T) {
})
}
}
// The workspace authorizes against its own org.json, so the registered member
// routes must carry a removal or demotion there, not only into the registry.
func TestRegisterRoutesMemberRemovalAndDemotionReachWorkspaceOrganization(t *testing.T) {
dir := t.TempDir()
reg, err := registry.NewTenantRegistry(dir)
if err != nil {
t.Fatal(err)
}
defer reg.Close()
const accountID, tenantID = "a-route-members", "t-route-members"
if err := reg.CreateAccount(&registry.Account{ID: accountID, Kind: registry.AccountKindMSP}); err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
org := &models.Organization{ID: tenantID, DisplayName: "Client", Status: models.OrgStatusActive, CreatedAt: now, OwnerUserID: "u-owner", OwnerEmail: "owner@example.test"}
for userID, role := range map[string]registry.MemberRole{"u-owner": registry.MemberRoleOwner, "u-removed": registry.MemberRoleAdmin, "u-demoted": registry.MemberRoleAdmin} {
email := strings.TrimPrefix(userID, "u-") + "@example.test"
if err := reg.CreateUser(&registry.User{ID: userID, Email: email}); err != nil {
t.Fatal(err)
}
if err := reg.CreateMembership(&registry.AccountMembership{AccountID: accountID, UserID: userID, Role: role}); err != nil {
t.Fatal(err)
}
org.Members = append(org.Members, models.OrganizationMember{UserID: userID, Email: email, Role: models.OrganizationRoleFromAccountRole(string(role)), AddedAt: now, AddedBy: "u-owner"})
}
if err := reg.Create(&registry.Tenant{ID: tenantID, AccountID: accountID, State: registry.TenantStateActive, PlanVersion: "msp_starter"}); err != nil {
t.Fatal(err)
}
session, err := cpauth.NewService(dir)
if err != nil {
t.Fatal(err)
}
defer session.Close()
cfg := &CPConfig{DataDir: dir, BaseURL: "https://cloud.example.com", AdminKey: "fixture-only", ControlPlaneMode: ControlPlaneModeProviderHostedMSP}
workspace := config.NewMultiTenantPersistence(filepath.Join(cfg.TenantsDir(), tenantID))
if err := workspace.SaveOrganization(org); err != nil {
t.Fatal(err)
}
mux := http.NewServeMux()
RegisterRoutes(mux, &Deps{Config: cfg, Registry: reg, MagicLinks: session})
token, err := session.GenerateSessionToken("u-owner", "owner@example.test", time.Hour)
if err != nil {
t.Fatal(err)
}
do := func(method, userID, body string, want int) {
t.Helper()
req := httptest.NewRequest(method, "https://cloud.example.com/api/accounts/"+accountID+"/members/"+userID, strings.NewReader(body))
req.AddCookie(&http.Cookie{Name: cpauth.SessionCookieName, Value: token})
res := httptest.NewRecorder()
mux.ServeHTTP(res, req)
if res.Code != want {
t.Fatalf("%s %s = %d %s, want %d", method, userID, res.Code, res.Body.String(), want)
}
}
do(http.MethodDelete, "u-removed", "", http.StatusNoContent)
do(http.MethodPatch, "u-demoted", `{"role":"read_only"}`, http.StatusOK)
stored, err := workspace.LoadOrganizationStrict(tenantID)
if err != nil {
t.Fatal(err)
}
if stored.CanUserIDAccess("u-removed") {
t.Fatalf("removed account member is still a workspace member: %+v", stored.Members)
}
if got := stored.GetMemberRoleByUserID("u-demoted"); got != models.OrgRoleViewer {
t.Fatalf("demoted account member has workspace role %q, want %q", got, models.OrgRoleViewer)
}
if stored.OwnerUserID != "u-owner" || stored.GetMemberRoleByUserID("u-owner") != models.OrgRoleOwner {
t.Fatalf("workspace owner changed: %q %+v", stored.OwnerUserID, stored.Members)
}
// Undoing a demotion and re-inviting a removed member restore workspace access.
do(http.MethodPatch, "u-demoted", `{"role":"admin"}`, http.StatusOK)
inviteReq := httptest.NewRequest(http.MethodPost, "https://cloud.example.com/api/accounts/"+accountID+"/members", strings.NewReader(`{"email":"removed@example.test","role":"tech"}`))
inviteReq.AddCookie(&http.Cookie{Name: cpauth.SessionCookieName, Value: token})
inviteRes := httptest.NewRecorder()
mux.ServeHTTP(inviteRes, inviteReq)
if inviteRes.Code != http.StatusCreated {
t.Fatalf("POST re-invite = %d %s, want %d", inviteRes.Code, inviteRes.Body.String(), http.StatusCreated)
}
stored, err = workspace.LoadOrganizationStrict(tenantID)
if err != nil {
t.Fatal(err)
}
if got := stored.GetMemberRoleByUserID("u-demoted"); got != models.OrgRoleAdmin {
t.Fatalf("restored admin has workspace role %q, want %q", got, models.OrgRoleAdmin)
}
if got := stored.GetMemberRoleByUserID("u-removed"); got != models.OrgRoleEditor {
t.Fatalf("re-invited member has workspace role %q, want %q", got, models.OrgRoleEditor)
}
}
+385
View File
@@ -0,0 +1,385 @@
package stripe
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rs/zerolog/log"
)
// The control plane shares org.json with the running workspace, and a save over
// a snapshot that is no longer current is refused. Each attempt reloads the
// organization and derives the revocation from what it holds then, so nothing
// from an earlier snapshot is written back.
const workspaceAccessSaveAttempts = 5
// RevokeWorkspaceAccess removes an account member from every workspace of the
// account.
//
// A workspace authorizes each request against its own org.json. That file is
// seeded from the account's members when the workspace is provisioned and is
// never read back from the registry, so a removal that only reaches the
// registry stops new handoffs but leaves the member's row, and with it every
// workspace session the member already holds, in place.
func (p *Provisioner) RevokeWorkspaceAccess(ctx context.Context, accountID, userID string) error {
return p.limitWorkspaceAccess(ctx, accountID, userID, "")
}
// LowerWorkspaceAccess caps an account member's role in every workspace of the
// account at the organization role of their new, lower account role. The
// handoff admits a member with the role stored in the workspace, so without
// this a demoted member keeps the earlier role in open and in new sessions.
func (p *Provisioner) LowerWorkspaceAccess(ctx context.Context, accountID, userID string, role registry.MemberRole) error {
return p.limitWorkspaceAccess(ctx, accountID, userID, models.OrganizationRoleFromAccountRole(string(role)))
}
// SyncWorkspaceAccess ensures an account member is present in every workspace
// of the account with at least the organization role mapped from their account
// role. This keeps undoing a demotion or re-inviting a removed member working
// across existing workspaces while preserving any higher workspace-local grant.
func (p *Provisioner) SyncWorkspaceAccess(ctx context.Context, accountID, userID string, role registry.MemberRole) error {
accountID = strings.TrimSpace(accountID)
userID = strings.TrimSpace(userID)
if p == nil || p.registry == nil {
return fmt.Errorf("workspace access is unavailable")
}
if accountID == "" || userID == "" {
return fmt.Errorf("account id and user id are required")
}
floor := models.OrganizationRoleFromAccountRole(string(role))
if !models.IsValidOrganizationRole(floor) {
return fmt.Errorf("invalid account role %q", role)
}
email := ""
user, err := p.registry.GetUser(userID)
if err != nil {
return fmt.Errorf("get account user %s: %w", userID, err)
}
if user != nil {
email = strings.ToLower(strings.TrimSpace(user.Email))
}
tenants, err := p.registry.ListByAccountID(accountID)
if err != nil {
return fmt.Errorf("list workspaces for %s: %w", accountID, err)
}
var problems []error
for _, tenant := range tenants {
if tenant == nil {
continue
}
if err := ctx.Err(); err != nil {
problems = append(problems, err)
break
}
if err := p.syncWorkspaceMemberAccess(accountID, tenant.ID, userID, email, floor); err != nil {
problems = append(problems, fmt.Errorf("workspace %s: %w", tenant.ID, err))
}
}
return errors.Join(problems...)
}
func (p *Provisioner) syncWorkspaceMemberAccess(accountID, tenantID, userID, email string, floor models.OrganizationRole) error {
tenantDataDir := p.tenantDataDir(tenantID)
orgFile := filepath.Join(tenantDataDir, "orgs", tenantID, "org.json")
if _, err := os.Stat(orgFile); errors.Is(err, os.ErrNotExist) {
return nil
}
mtp := config.NewMultiTenantPersistence(tenantDataDir)
for attempt := 1; ; attempt++ {
org, err := mtp.LoadOrganizationStrict(tenantID)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("load organization metadata: %w", err)
}
changed := syncOrganizationMemberAccess(org, userID, email, floor)
if !changed {
return nil
}
err = mtp.SaveOrganization(org)
if errors.Is(err, config.ErrOrganizationChanged) && attempt < workspaceAccessSaveAttempts {
continue
}
if err != nil {
return fmt.Errorf("save organization metadata: %w", err)
}
if err := p.ensureHostedRuntimeFileOwnership(orgFile); err != nil {
return fmt.Errorf("set organization metadata ownership: %w", err)
}
log.Info().
Str("account_id", accountID).
Str("tenant_id", tenantID).
Str("user_id", userID).
Str("role_floor", string(floor)).
Msg("Synced account member role into workspace organization")
return nil
}
}
func syncOrganizationMemberAccess(org *models.Organization, userID, email string, floor models.OrganizationRole) bool {
matches := func(storedUserID string) bool {
storedUserID = strings.TrimSpace(storedUserID)
if storedUserID == "" {
return false
}
return storedUserID == userID ||
(email != "" && strings.Contains(storedUserID, "@") && strings.ToLower(storedUserID) == email)
}
matched := false
changed := false
for i := range org.Members {
if !matches(org.Members[i].UserID) {
continue
}
matched = true
if !models.OrganizationRoleAtLeast(org.Members[i].Role, floor) {
org.Members[i].Role = floor
changed = true
}
if org.Members[i].Email == "" && email != "" {
org.Members[i].Email = email
changed = true
}
}
if !matched {
org.Members = append(org.Members, models.OrganizationMember{
UserID: userID,
Email: email,
Role: floor,
AddedAt: time.Now().UTC(),
AddedBy: userID,
})
changed = true
}
return changed
}
// limitWorkspaceAccess takes no runtime lifecycle lease: a rollout, a health
// check or an unfinished recovery on one workspace must not keep access in
// place in the others, or keep the member in the account. Every workspace is
// attempted; the caller keeps the account membership as it was when any of
// them fails, so the change can be retried.
func (p *Provisioner) limitWorkspaceAccess(ctx context.Context, accountID, userID string, ceiling models.OrganizationRole) error {
accountID = strings.TrimSpace(accountID)
userID = strings.TrimSpace(userID)
if p == nil || p.registry == nil {
return fmt.Errorf("workspace access is unavailable")
}
if accountID == "" || userID == "" {
return fmt.Errorf("account id and user id are required")
}
email := ""
user, err := p.registry.GetUser(userID)
if err != nil {
return fmt.Errorf("get account user %s: %w", userID, err)
}
if user != nil {
email = strings.ToLower(strings.TrimSpace(user.Email))
}
tenants, err := p.registry.ListByAccountID(accountID)
if err != nil {
return fmt.Errorf("list workspaces for %s: %w", accountID, err)
}
var problems []error
for _, tenant := range tenants {
if tenant == nil {
continue
}
if err := ctx.Err(); err != nil {
problems = append(problems, err)
break
}
if err := p.limitWorkspaceMemberAccess(accountID, tenant.ID, userID, email, ceiling); err != nil {
problems = append(problems, fmt.Errorf("workspace %s: %w", tenant.ID, err))
}
}
return errors.Join(problems...)
}
func (p *Provisioner) limitWorkspaceMemberAccess(accountID, tenantID, userID, email string, ceiling models.OrganizationRole) error {
tenantDataDir := p.tenantDataDir(tenantID)
orgFile := filepath.Join(tenantDataDir, "orgs", tenantID, "org.json")
if _, err := os.Stat(orgFile); errors.Is(err, os.ErrNotExist) {
// No organization metadata: the workspace admits nobody yet.
return nil
}
mtp := config.NewMultiTenantPersistence(tenantDataDir)
for attempt := 1; ; attempt++ {
org, err := mtp.LoadOrganizationStrict(tenantID)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("load organization metadata: %w", err)
}
changed, err := p.limitOrganizationMemberAccess(org, accountID, userID, email, ceiling)
if err != nil {
return err
}
if !changed {
return nil
}
err = mtp.SaveOrganization(org)
if errors.Is(err, config.ErrOrganizationChanged) && attempt < workspaceAccessSaveAttempts {
continue
}
if err != nil {
return fmt.Errorf("save organization metadata: %w", err)
}
if err := p.ensureHostedRuntimeFileOwnership(orgFile); err != nil {
return fmt.Errorf("set organization metadata ownership: %w", err)
}
event := "Removed account member from workspace organization"
if ceiling != "" {
event = "Lowered account member role in workspace organization"
}
log.Info().
Str("account_id", accountID).
Str("tenant_id", tenantID).
Str("user_id", userID).
Str("role_ceiling", string(ceiling)).
Str("owner_user_id", org.OwnerUserID).
Msg(event)
return nil
}
}
// limitOrganizationMemberAccess removes the principal from the organization,
// or, given a ceiling, lowers a stored role above it. It matches what the
// handoff admits: the stable user ID, or a legacy record keyed by the email.
// An organization the principal owns passes to another account owner.
func (p *Provisioner) limitOrganizationMemberAccess(org *models.Organization, accountID, userID, email string, ceiling models.OrganizationRole) (bool, error) {
matches := func(storedUserID string) bool {
storedUserID = strings.TrimSpace(storedUserID)
if storedUserID == "" {
return false
}
return storedUserID == userID ||
(email != "" && strings.Contains(storedUserID, "@") && strings.ToLower(storedUserID) == email)
}
exceedsCeiling := func(role models.OrganizationRole) bool {
return models.IsValidOrganizationRole(role) && !models.OrganizationRoleAtLeast(ceiling, role)
}
changed := false
newOwnerUserID := ""
if matches(org.OwnerUserID) && ceiling != models.OrgRoleOwner {
successor, err := p.workspaceOwnerSuccessor(accountID, userID)
if err != nil {
return false, err
}
// Without another account owner the workspace is left without one
// rather than with the owner whose access is being taken away.
org.OwnerUserID, org.OwnerEmail = "", ""
if successor != nil {
newOwnerUserID = strings.TrimSpace(successor.ID)
org.OwnerUserID = newOwnerUserID
org.OwnerEmail = strings.ToLower(strings.TrimSpace(successor.Email))
}
changed = true
}
members := make([]models.OrganizationMember, 0, len(org.Members)+1)
newOwnerIsMember := false
for _, member := range org.Members {
switch {
case matches(member.UserID):
if ceiling == "" {
changed = true
continue
}
if exceedsCeiling(member.Role) {
member.Role = ceiling
changed = true
}
case newOwnerUserID != "" && strings.TrimSpace(member.UserID) == newOwnerUserID:
member.Role = models.OrgRoleOwner
newOwnerIsMember = true
}
members = append(members, member)
}
if newOwnerUserID != "" && !newOwnerIsMember {
members = append(members, models.OrganizationMember{
UserID: newOwnerUserID,
Email: org.OwnerEmail,
Role: models.OrgRoleOwner,
AddedAt: time.Now().UTC(),
AddedBy: newOwnerUserID,
})
}
// An invitation still pending in the workspace could otherwise be accepted
// from a session the principal already holds.
invitations := make([]models.OrganizationInvitation, 0, len(org.PendingInvitations))
for _, invitation := range org.PendingInvitations {
if matches(invitation.UserID) {
if ceiling == "" {
changed = true
continue
}
if exceedsCeiling(invitation.Role) {
invitation.Role = ceiling
changed = true
}
}
invitations = append(invitations, invitation)
}
if changed {
org.Members = members
org.PendingInvitations = invitations
}
return changed, nil
}
// workspaceOwnerSuccessor returns the account's longest-standing owner other
// than userID, the owner buildSeededTenantOrganization gives a workspace that
// is provisioned without a named one. It returns nil when there is none.
func (p *Provisioner) workspaceOwnerSuccessor(accountID, userID string) (*registry.User, error) {
memberships, err := p.registry.ListMembersByAccount(accountID)
if err != nil {
return nil, fmt.Errorf("list account members for %s: %w", accountID, err)
}
var successor *registry.AccountMembership
for _, membership := range memberships {
if membership == nil || membership.Role != registry.MemberRoleOwner {
continue
}
candidateID := strings.TrimSpace(membership.UserID)
if candidateID == "" || candidateID == userID {
continue
}
if successor == nil ||
membership.CreatedAt.Before(successor.CreatedAt) ||
(membership.CreatedAt.Equal(successor.CreatedAt) && candidateID < strings.TrimSpace(successor.UserID)) {
successor = membership
}
}
if successor == nil {
return nil, nil
}
user, err := p.registry.GetUser(successor.UserID)
if err != nil {
return nil, fmt.Errorf("get account user %s: %w", successor.UserID, err)
}
if user == nil || strings.TrimSpace(user.ID) == "" {
return nil, fmt.Errorf("account membership references missing user %s", successor.UserID)
}
return user, nil
}
@@ -0,0 +1,219 @@
package stripe
import (
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/account"
"github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
)
// A workspace authorizes against its own org.json, so removing or demoting an
// account member has to be written there too, not only to the registry.
func TestAccountMemberRemovalAndDemotionReachWorkspaces(t *testing.T) {
reg := newStripeTestRegistry(t)
tenantsDir := t.TempDir()
p := newTestProvisioner(t, reg, tenantsDir, nil, true)
var chowned []string
p.chownFile = func(path string, _, _ int) error {
chowned = append(chowned, path)
return nil
}
const accountID, otherAccountID = "a-access", "a-other"
for _, id := range []string{accountID, otherAccountID} {
if err := reg.CreateAccount(&registry.Account{ID: id, Kind: registry.AccountKindMSP}); err != nil {
t.Fatal(err)
}
seedWorkspaceBilling(t, reg, id)
}
users := map[string]registry.MemberRole{
"u_owner": registry.MemberRoleOwner,
"u_admin": registry.MemberRoleAdmin,
"u_tech": registry.MemberRoleTech,
}
for userID, role := range users {
email := strings.TrimPrefix(userID, "u_") + "@msp.example"
if err := reg.CreateUser(&registry.User{ID: userID, Email: email}); err != nil {
t.Fatal(err)
}
for _, id := range []string{accountID, otherAccountID} {
if err := reg.CreateMembership(&registry.AccountMembership{AccountID: id, UserID: userID, Role: role}); err != nil {
t.Fatal(err)
}
}
}
ctx := context.Background()
// The admin created this workspace and so owns it.
adminOwned, err := p.ProvisionWorkspaceForOwner(ctx, accountID, "Admin's client", "admin@msp.example")
if err != nil {
t.Fatalf("ProvisionWorkspaceForOwner: %v", err)
}
shared, err := p.ProvisionWorkspace(ctx, accountID, "Client")
if err != nil {
t.Fatalf("ProvisionWorkspace: %v", err)
}
other, err := p.ProvisionWorkspace(ctx, otherAccountID, "Other account's client")
if err != nil {
t.Fatalf("ProvisionWorkspace: %v", err)
}
loadOrg := func(tenantID string) *models.Organization {
t.Helper()
org, err := config.NewMultiTenantPersistence(filepath.Join(tenantsDir, tenantID)).LoadOrganizationStrict(tenantID)
if err != nil {
t.Fatalf("LoadOrganizationStrict(%s): %v", tenantID, err)
}
return org
}
sharedOrg := loadOrg(shared.ID)
sharedOrg.PendingInvitations = append(sharedOrg.PendingInvitations, models.OrganizationInvitation{
UserID: "u_tech", Role: models.OrgRoleAdmin, InvitedAt: time.Now().UTC(), InvitedBy: "u_owner",
})
if err := config.NewMultiTenantPersistence(filepath.Join(tenantsDir, shared.ID)).SaveOrganization(sharedOrg); err != nil {
t.Fatalf("SaveOrganization: %v", err)
}
for _, tenantID := range []string{adminOwned.ID, shared.ID, other.ID} {
org := loadOrg(tenantID)
if got := org.GetMemberRoleByUserID("u_admin"); !models.OrganizationRoleAtLeast(got, models.OrgRoleAdmin) {
t.Fatalf("seeded role of u_admin in %s = %q", tenantID, got)
}
if got := org.GetMemberRoleByUserID("u_tech"); got != models.OrgRoleEditor {
t.Fatalf("seeded role of u_tech in %s = %q", tenantID, got)
}
}
if got := loadOrg(adminOwned.ID).OwnerUserID; got != "u_admin" {
t.Fatalf("seeded owner = %q, want u_admin", got)
}
chowned = nil
mux := http.NewServeMux()
mux.Handle("PATCH /api/accounts/{account_id}/members/{user_id}", account.HandleUpdateMemberRole(reg, p))
mux.Handle("DELETE /api/accounts/{account_id}/members/{user_id}", account.HandleRemoveMember(reg, p))
do := func(method, userID, body string, want int) {
t.Helper()
req := httptest.NewRequest(method, "/api/accounts/"+accountID+"/members/"+userID, strings.NewReader(body))
req.Header.Set("X-User-Role", string(registry.MemberRoleOwner))
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != want {
t.Fatalf("%s %s: status = %d, want %d (body=%q)", method, userID, rec.Code, want, rec.Body.String())
}
}
do(http.MethodPatch, "u_admin", `{"role":"read_only"}`, http.StatusOK)
for _, tenantID := range []string{adminOwned.ID, shared.ID} {
if got := loadOrg(tenantID).GetMemberRoleByUserID("u_admin"); got != models.OrgRoleViewer {
t.Fatalf("role of demoted u_admin in %s = %q, want %q", tenantID, got, models.OrgRoleViewer)
}
}
org := loadOrg(adminOwned.ID)
if org.OwnerUserID != "u_owner" || org.OwnerEmail != "owner@msp.example" || org.GetMemberRoleByUserID("u_owner") != models.OrgRoleOwner {
t.Fatalf("workspace owned by the demoted member passed to %q (%q), owner role %q", org.OwnerUserID, org.OwnerEmail, org.GetMemberRoleByUserID("u_owner"))
}
if len(chowned) != 2 {
t.Fatalf("rewritten org.json files given runtime ownership = %v, want both workspaces", chowned)
}
// Raising an account role restores the corresponding workspace role floor
// across the account's existing workspaces.
do(http.MethodPatch, "u_admin", `{"role":"tech"}`, http.StatusOK)
for _, tenantID := range []string{adminOwned.ID, shared.ID} {
if got := loadOrg(tenantID).GetMemberRoleByUserID("u_admin"); got != models.OrgRoleEditor {
t.Fatalf("role of re-promoted u_admin in %s = %q, want %q", tenantID, got, models.OrgRoleEditor)
}
}
do(http.MethodDelete, "u_tech", "", http.StatusNoContent)
for _, tenantID := range []string{adminOwned.ID, shared.ID} {
org := loadOrg(tenantID)
if org.CanUserAccess("u_tech") || org.CanUserAccess("tech@msp.example") {
t.Fatalf("removed member still has access to %s: %+v", tenantID, org.Members)
}
if !org.CanUserIDAccess("u_owner") || !org.CanUserIDAccess("u_admin") {
t.Fatalf("removal of u_tech dropped other members of %s: %+v", tenantID, org.Members)
}
}
if invitations := loadOrg(shared.ID).PendingInvitations; len(invitations) != 0 {
t.Fatalf("removed member keeps a pending invitation: %+v", invitations)
}
// Membership of another account is a separate grant.
org = loadOrg(other.ID)
if org.GetMemberRoleByUserID("u_tech") != models.OrgRoleEditor || org.GetMemberRoleByUserID("u_admin") != models.OrgRoleAdmin {
t.Fatalf("another account's workspace changed: %+v", org.Members)
}
}
// Legacy organization records are keyed by email; the handoff still admits
// them, so a removal has to find them as well.
func TestRevokeWorkspaceAccessRemovesLegacyEmailKeyedMember(t *testing.T) {
reg := newStripeTestRegistry(t)
tenantsDir := t.TempDir()
p := newTestProvisioner(t, reg, tenantsDir, nil, true)
const accountID = "a-legacy"
if err := reg.CreateAccount(&registry.Account{ID: accountID, Kind: registry.AccountKindMSP}); err != nil {
t.Fatal(err)
}
seedWorkspaceBilling(t, reg, accountID)
for userID, role := range map[string]registry.MemberRole{"u_owner": registry.MemberRoleOwner, "u_tech": registry.MemberRoleTech} {
if err := reg.CreateUser(&registry.User{ID: userID, Email: strings.TrimPrefix(userID, "u_") + "@msp.example"}); err != nil {
t.Fatal(err)
}
if err := reg.CreateMembership(&registry.AccountMembership{AccountID: accountID, UserID: userID, Role: role}); err != nil {
t.Fatal(err)
}
}
tenant, err := p.ProvisionWorkspace(context.Background(), accountID, "Client")
if err != nil {
t.Fatalf("ProvisionWorkspace: %v", err)
}
mtp := config.NewMultiTenantPersistence(filepath.Join(tenantsDir, tenant.ID))
org, err := mtp.LoadOrganizationStrict(tenant.ID)
if err != nil {
t.Fatal(err)
}
for i := range org.Members {
if org.Members[i].UserID == "u_tech" {
org.Members[i].UserID, org.Members[i].Email = "Tech@MSP.example", ""
}
}
if err := mtp.SaveOrganization(org); err != nil {
t.Fatal(err)
}
if err := p.RevokeWorkspaceAccess(context.Background(), accountID, "u_tech"); err != nil {
t.Fatalf("RevokeWorkspaceAccess: %v", err)
}
org, err = mtp.LoadOrganizationStrict(tenant.ID)
if err != nil {
t.Fatal(err)
}
if got := org.GetMemberRoleForPrincipal("u_tech", "tech@msp.example"); got != "" {
t.Fatalf("removed member is still admitted with role %q: %+v", got, org.Members)
}
if len(org.Members) != 1 || org.Members[0].UserID != "u_owner" {
t.Fatalf("members after removal = %+v, want only u_owner", org.Members)
}
// Re-adding the removed member restores their membership in the workspace.
if err := p.SyncWorkspaceAccess(context.Background(), accountID, "u_tech", registry.MemberRoleAdmin); err != nil {
t.Fatalf("SyncWorkspaceAccess: %v", err)
}
org, err = mtp.LoadOrganizationStrict(tenant.ID)
if err != nil {
t.Fatal(err)
}
if got := org.GetMemberRoleByUserID("u_tech"); got != models.OrgRoleAdmin {
t.Fatalf("re-synced member role = %q, want %q", got, models.OrgRoleAdmin)
}
}
+2
View File
@@ -48,6 +48,8 @@ func (l *AsyncLogger) Record(event Event) error {
if l == nil {
return nil
}
// Bound the event here as well: the queue holds it until the backend does.
event = boundEvent(event)
if l.closed.Load() {
return l.backend.Record(event)
}
+45
View File
@@ -13,6 +13,7 @@ import (
"encoding/hex"
"sync"
"time"
"unicode/utf8"
"github.com/google/uuid"
"github.com/rs/zerolog"
@@ -32,6 +33,48 @@ type Event struct {
Signature string `json:"signature,omitempty"` // Empty for OSS, HMAC for enterprise
}
// Bounds on the text of a recorded event. Event text can come from requests
// that carry no credentials (the user name of a failed Basic sign-in, the
// request path, an identity provider's error), while readers bound only how
// many events they hold in memory: up to MaxExportEvents, whose JSON can take
// six bytes for each byte of text. The user bound keeps the longest local
// user name (128 characters of up to four bytes) whole, so filtering by user
// still finds its events.
const (
maxEventTypeBytes = 64
maxEventUserBytes = 512
maxEventIPBytes = 64
maxEventPathBytes = 512
maxEventDetailsBytes = 1024
eventTruncationTag = "...[truncated]"
)
// boundEvent bounds event text before it is queued, signed or stored, so the
// signature covers exactly what is kept. Events that fit are unchanged.
func boundEvent(event Event) Event {
event.EventType = boundEventText(event.EventType, maxEventTypeBytes)
event.User = boundEventText(event.User, maxEventUserBytes)
event.IP = boundEventText(event.IP, maxEventIPBytes)
event.Path = boundEventText(event.Path, maxEventPathBytes)
event.Details = boundEventText(event.Details, maxEventDetailsBytes)
return event
}
func boundEventText(text string, maxBytes int) string {
if len(text) <= maxBytes {
return text
}
end := maxBytes - len(eventTruncationTag)
// Do not split a multi-byte character.
for back := 1; back < utf8.UTFMax && end > 0 && !utf8.RuneStart(text[end]); back++ {
end--
}
// The concatenation copies the kept prefix: the oversized original is not
// retained by the event.
return text[:end] + eventTruncationTag
}
// QueryFilter defines filters for querying audit events.
type QueryFilter struct {
ID string
@@ -214,6 +257,8 @@ func (c *ConsoleLogger) IsPersistentAuditLogger() bool {
// Record writes a redacted audit event projection to zerolog.
func (c *ConsoleLogger) Record(event Event) error {
event = boundEvent(event)
logContext := log.With().
Str("audit_id", event.ID).
Str("event", event.EventType).
+125
View File
@@ -0,0 +1,125 @@
package audit
import (
"strings"
"testing"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
func TestBoundEventTextKeepsFittingTextAndCutsOnCharacterBoundaries(t *testing.T) {
fitting := strings.Repeat("界", maxEventUserBytes/3)
if got := boundEventText(fitting, maxEventUserBytes); got != fitting {
t.Fatalf("fitting text was changed: %d bytes, want %d", len(got), len(fitting))
}
for _, oversized := range []string{
strings.Repeat("\x01", 750_000),
strings.Repeat("界", 250_000),
"a" + strings.Repeat("🔐", 200_000),
strings.Repeat("\x80", 750_000),
} {
got := boundEventText(oversized, maxEventUserBytes)
if len(got) > maxEventUserBytes {
t.Fatalf("bounded text has %d bytes, want at most %d", len(got), maxEventUserBytes)
}
if len(got) < maxEventUserBytes-utf8.UTFMax {
t.Fatalf("bounded text has only %d bytes", len(got))
}
if !strings.HasSuffix(got, eventTruncationTag) {
t.Fatalf("bounded text does not say it was truncated: %q", got[len(got)-32:])
}
kept := strings.TrimSuffix(got, eventTruncationTag)
if !strings.HasPrefix(oversized, kept) {
t.Fatal("bounded text is not a prefix of the original")
}
if utf8.ValidString(oversized) && !utf8.ValidString(got) {
t.Fatal("bounding split a multi-byte character")
}
}
}
func TestSQLiteLoggerRecordBoundsEventTextBeforeSigning(t *testing.T) {
logger, err := NewSQLiteLogger(SQLiteLoggerConfig{
DataDir: t.TempDir(),
CryptoMgr: newMockCryptoManager(),
})
if err != nil {
t.Fatalf("NewSQLiteLogger failed: %v", err)
}
defer logger.Close()
// The user name of a failed Basic sign-in and the request path are chosen
// by a client without credentials.
oversized := strings.Repeat("\x01", 750_000)
event := Event{
ID: uuid.NewString(),
Timestamp: time.Now(),
EventType: "login",
User: oversized,
IP: "203.0.113.66",
Path: "/api/" + oversized,
Success: false,
Details: oversized,
}
if err := logger.Record(event); err != nil {
t.Fatalf("Record failed: %v", err)
}
events, err := logger.Query(QueryFilter{ID: event.ID})
if err != nil {
t.Fatalf("Query failed: %v", err)
}
if len(events) != 1 {
t.Fatalf("Query returned %d events, want 1", len(events))
}
stored := events[0]
for name, field := range map[string]struct {
text string
max int
}{
"user": {stored.User, maxEventUserBytes},
"path": {stored.Path, maxEventPathBytes},
"details": {stored.Details, maxEventDetailsBytes},
} {
if len(field.text) != field.max || !strings.HasSuffix(field.text, eventTruncationTag) {
t.Errorf("stored %s has %d bytes, want %d ending in the truncation tag", name, len(field.text), field.max)
}
}
if stored.EventType != event.EventType || stored.IP != event.IP {
t.Errorf("fitting fields were changed: event %q, ip %q", stored.EventType, stored.IP)
}
if !logger.VerifySignature(stored) {
t.Error("the signature does not cover the stored, bounded event")
}
}
type recordingLogger struct {
ConsoleLogger
recorded chan Event
}
func (l *recordingLogger) Record(event Event) error {
l.recorded <- event
return nil
}
func TestAsyncLoggerBoundsEventTextBeforeQueueing(t *testing.T) {
backend := &recordingLogger{recorded: make(chan Event, 1)}
logger := NewAsyncLogger(backend, AsyncLoggerConfig{BufferSize: 1})
defer logger.Close()
if err := logger.Record(Event{ID: "oversized", EventType: "login", User: strings.Repeat("\x01", 750_000)}); err != nil {
t.Fatalf("Record failed: %v", err)
}
select {
case event := <-backend.recorded:
if len(event.User) != maxEventUserBytes {
t.Fatalf("queued user has %d bytes, want %d", len(event.User), maxEventUserBytes)
}
case <-time.After(5 * time.Second):
t.Fatal("the backend did not receive the event")
}
}
+4
View File
@@ -546,6 +546,10 @@ func auditEventsNeedRebuild(tx *sql.Tx) (bool, error) {
// Log records an audit event with HMAC signature.
func (l *SQLiteLogger) Record(event Event) error {
// Every stored event passes here. Bound its text before it is signed:
// readers hold whole pages and exports of stored events in memory.
event = boundEvent(event)
// Sign the event
event.Signature = l.signer.Sign(event)