Commit Graph

7 Commits

Author SHA1 Message Date
xarmian d895418ea2 fix(server): gate RequireAuth's cloud-secret bypass on validated session (BUG-1944) (#1112)
Sibling of TASK-1932's CSRFProtect fix: RequireAuth's isCloudAdminPath +
hasCloudSecretMarker bypass fired on marker presence, not validated secret.
Mirror TASK-1932's currentUser(r) == nil gate exactly. Concretely closes a
disabled-admin gap: without the gate, a marker with the wrong secret let
RequireAuth's own user.IsDisabled() check be skipped whenever a session was
present, reaching handlers that trust a resolved admin session as an
alternative to validateCloudSecret. In-handler validation for every
cloudAdminPaths handler is unchanged and remains the independent layer for
the genuine no-session sidecar case.
2026-08-15 19:18:55 -04:00
xarmian 7cda0d7896 feat: rebrand to Perpetual Software + new tagline (IDEA-832) (#273)
Migrates from xarmian/pad to PerpetualSoftware/pad across the entire
repo and updates the product subtitle to "Collaborate with your AI
agents".

Go module rename
- go.mod: github.com/xarmian/pad → github.com/PerpetualSoftware/pad
- All Go imports updated across cmd/pad, internal/{cli,server,store,
  models,collections,items,events,metrics,webhooks} (~130 files)
- Test fixtures with the literal repo slug ("xarmian/pad" in JSON
  shapes, SSH/HTTPS git URL strings, workspace_context fixtures)
  also updated, including the secondary repo entry
  (xarmian/pad-web → PerpetualSoftware/pad-web — pad-web was also
  moved to the org per branch context)

Docs / config
- README badges, install instructions, brew tap, Docker image, source
  build path, sponsor link (sponsor link kept as personal @xarmian)
- Subtitle: "Project management for developers and AI agents." →
  "Collaborate with your AI agents." (README, manifests, web layout
  meta, .goreleaser homebrew description)
- CONTRIBUTING.md, SECURITY.md, skills/INSTALL.md
- .goreleaser.yaml: homebrew_casks owner, GHCR image, release github
  owner, cosign cert-identity regex, comments
- .github/workflows/release.yml: tap/release comments
- deploy/k8s/deployment.yaml: container image
- docs/deployment.md: clone URL
- web/static/{site.webmanifest,manifest.json}: description
- web/src/routes/+layout.svelte: meta description + og:description

Brew tap path is PerpetualSoftware/tap/pad (CamelCase, matches
GitHub user case). GHCR image is ghcr.io/perpetualsoftware/pad
(lowercased per GHCR's URL normalization). CODEOWNERS @xarmian and
FUNDING.yml github: xarmian intentionally retained — those are the
personal maintainer / sponsor account, separate from the org repo.

Verification: go build ./..., go test ./... (all pkgs pass), web
build, and make install all clean (TASK-844, TASK-845).
2026-04-28 12:26:39 -04:00
xarmian 119e2d8aa2 feat(billing): payment-failed email endpoint + template (TASK-712 1 of 2) (#232)
* feat(billing): payment-failed email endpoint + template (TASK-712 1 of 2)

Pairs with pad-cloud's invoice.payment_failed webhook handler (shipping
next) to give paying users a chance to update their card before dunning
exhausts and the subscription cancels. pad owns the Maileroo integration
and the user→email mapping; the sidecar forwards the invoice metadata
here.

Changes:

- email.Sender.SendPaymentFailed — new template (HTML + plain). Subject
  "Your Pad payment couldn't be processed"; body names the amount +
  next retry date when provided, falls back to generic copy when Stripe
  omits them, and CTAs to the billing portal so the user can update
  their card. Transactional (no unsubscribe link) — users who want the
  emails to stop either fix their card or cancel the subscription.

- POST /api/v1/admin/payment-failed — new cloud-secret-gated endpoint
  (handlers_cloud.go). Accepts stripe_customer_id + optional pre-
  formatted amount_display + next_retry_display. Looks up the user,
  sends the email, logs a payment_failed_email_sent audit entry.
  Returns 200 + email_sent=false with a reason string for every
  non-error skip (unknown customer, no email on file, Maileroo not
  configured) so the sidecar never rolls back the Stripe webhook over
  an email failure. Returns 200 + email_sent=false + reason=send_failed
  when Maileroo itself errors — still no rollback.

- Registered the path in cloudAdminPaths, the server router, and the
  CloudAdmin rate limiter so the sidecar's calls share the same rate
  bucket as /plan + /stripe-customer-id.

- ActionPaymentFailedEmailSent audit constant for the new entry.

- Three focused tests: cus_ prefix validation, unknown-customer 200,
  and email-not-configured 200. Added an entry to the cloud-mode gate
  table-driven test to confirm /admin/payment-failed also 404s when
  cloud mode is off.

Parent: PLAN-645 (Pad Cloud Beta Readiness). TASK-712 bullet 3, pad
side. pad-cloud's handlePaymentFailed wiring ships in a sibling PR.

* fix(billing): audit every outcome; target user ID; add send-path tests (Codex round 1)

Addresses PR #232 round 1 findings:

MEDIUM — payment-failed handler only wrote an audit row on the actual
send attempt, so no_customer / no_email_address / email_not_configured
skip paths left no durable trail. Consolidated the audit + response
into a single auditAndRespond closure called from every outcome
branch, so operators can always reconstruct whether (and why) a
customer was notified during dunning reconciliation.

MEDIUM — audit UserID was set to actorID, which is empty for sidecar
calls. /audit-log?user=<target-user-id> would never surface these
events. Now set UserID to targetUser.ID whenever we have one; the
no_customer branch still writes a row but with empty UserID (filtered
only by action + stripe_customer_id metadata). Moved actor identity
into an actor_is_admin metadata field instead.

LOW — test coverage was thin: no assertion on the most important
contract ("return 200 with reason=send_failed and still record the
attempt"), no test of the happy send path, no audit-log assertions.
Added email.Sender.SetEndpoint (exported, test-only — comment says
so) so tests can point the Sender at a mock Maileroo server, plus
three new tests:
  - TestPaymentFailed_HappyPath_SendsAndAudits
  - TestPaymentFailed_MailerooError_Returns200_SendFailed_AndAudits
  - TestPaymentFailed_UnknownCustomer_AuditsWithoutUserID
The first two verify audit metadata per outcome; the third proves
unknown-customer cases still leave a findable audit row.

Thread-safety fix as a side-effect: Send/SendAs were reading s.endpoint
outside the sender's RWMutex — fine before the mutable SetEndpoint
existed, now a data race. Pulled the endpoint read into the same
RLock scope as fromAddr/fromName.

* fix: capture admin actor ID + audit-log formatter for payment_failed (Codex round 2)

Addresses PR #232 round 2 findings:

MEDIUM — auditAndRespond recorded actor_is_admin=true/false but not
which admin. For manual operator-triggered calls, that meant the audit
trail could not answer "who sent the dunning email?" when multiple
admins touched the endpoint. Added admin_actor_id to the metadata
whenever the authenticated caller has role=admin. Sidecar calls with
no authenticated user still have no admin_actor_id, which correctly
distinguishes them from manual admin operations.

LOW — web/src/routes/console/admin/audit-log/+page.svelte falls back
to "first 3 metadata keys" when no formatter exists for an action,
which could hide the important reason/sent fields. Added a dedicated
case for payment_failed_email_sent that renders either "sent (cus_...)"
or "skipped: <reason> (cus_...)" depending on the outcome, matching
the terse display style of the other switch cases.

* fix(audit-log): distinguish send_failed from skip; surface admin actor (Codex round 3)

Addresses PR #232 round 3 LOWs:

- The formatter lumped every sent=false outcome under 'skipped', which
  conflates a genuine Maileroo delivery failure with a pre-send skip.
  Now: sent → 'sent (...)'; send_failed → 'send failed (...)'; other
  reasons → 'skipped (<reason>) (...)'.
- admin_actor_id was recorded in metadata but invisible in the UI: the
  User column shows the target user via a.user_id. Appended
  'by admin:<id>' to the formatted string whenever admin_actor_id is
  present, so manual operator calls are attributable at a glance.
  Sidecar calls have no admin_actor_id and render without the suffix.

* fix(audit-log): register payment_failed_email_sent in action filter dropdown (Codex round 4)

The backend emits payment_failed_email_sent and the custom formatter
knows how to render it, but the audit-log page's ACTION_TYPES /
ACTION_LABELS registry omitted the action, so admins couldn't filter
for these events from the dropdown — undercutting the dunning
reconciliation workflow this PR is adding. Added 'payment_failed_email_sent'
to the ACTION_TYPES list and 'Payment Failed Email' to ACTION_LABELS.
2026-04-24 01:50:08 -04:00
xarmian 775dd89fdc feat(cloud): add /admin/stripe-event-unmark endpoint (TASK-736 / 1 of 2) (#228)
* feat(cloud): add /admin/stripe-event-unmark endpoint (TASK-736 / 1 of 2)

Parent: PLAN-645. Pair with pad-cloud follow-up.

* fix(cloud): add processed_at race protection + audit log per Codex review (round 1)
2026-04-23 20:26:02 -04:00
xarmian 0cbadf873b feat(server): durable Stripe webhook idempotency endpoint (TASK-696) (#226)
Adds a new cloud-gated admin endpoint that the pad-cloud sidecar uses
to record-or-detect-duplicate Stripe webhook events. Previously the
sidecar tracked processed event IDs in an in-memory map, which lost
state on restart and caused Stripe's 72h retries to re-run handlers.

Changes:

  migrations/045 + pgmigrations/025
    New stripe_processed_events(event_id PK, processed_at) table +
    index on processed_at for the pruning query.

  store/stripe_events.go
    MarkStripeEventProcessed(eventID) — INSERT ... ON CONFLICT DO
    NOTHING; returns alreadyProcessed from RowsAffected. Atomic.
    PruneStripeProcessedEvents(maxAge) — DELETE WHERE processed_at < ?.
    ShouldPruneStripeEvents() — ~1% random sample via crypto/rand.

  server/handlers_cloud.go
    handleStripeEventProcessed — POST /api/v1/admin/stripe-event-processed.
    Validates cloud_secret, requires event_id with 'evt_' prefix,
    returns {event_id, already_processed}. Opportunistically fires
    a background prune ~1% of calls (7-day retention window covers
    Stripe's 72h retry with a safe margin).

    Adds the new path to cloudAdminPaths so the secret-marker gate
    accepts X-Cloud-Secret / body-secret auth here too.

  server/server.go
    Registers POST /api/v1/admin/stripe-event-processed under the
    existing requireCloudMode group.

  server/middleware_ratelimit.go
    Adds the new path to the cloud-admin rate-limit bucket alongside
    /admin/plan, /admin/stripe-customer-id, /admin/user-by-customer.

  server/cloud_admin_gate_test.go
    Adds self-host-404 test case + two new tests:
      TestStripeEventProcessed_RecordsAndDetectsDuplicates
      TestStripeEventProcessed_ValidatesEventIDPrefix

Design notes in the PR body.

Parent: PLAN-645 (chunk 3).
2026-04-23 15:16:11 -04:00
xarmian f23113ab76 fix(server): drop cloud_secret query-param fallback (TASK-656) (#183)
handleGetUserByCustomerID accepted ?cloud_secret= for GET sidecar
calls. Query values land in access logs — our StructuredLogger records
path + raw query, and any fronting reverse proxy typically logs the
same. A log file compromise therefore became a compromise of the cloud
trust boundary.

Remove the fallback in two places:

1. handleGetUserByCustomerID — only checks X-Cloud-Secret header now
   (or admin auth via cookie/token). Comment explains why the
   convenience fallback was removed.
2. hasCloudSecretMarker — no longer honors ?cloud_secret on the
   auth/CSRF bypass path. Header or body-only for POSTs.

Sidecars must send Authorization via the X-Cloud-Secret header. Pad
Cloud deployment needs to be updated in lockstep; release notes should
call this out.

Tests:
- TestCloudAdminGate_QueryParamSecret_Rejected flips the prior
  backward-compat test: ?cloud_secret on /user-by-customer now returns
  401 (was 404 pre-fix).
- TestCloudAdminGate_HeaderSecret_StillAuthenticates confirms the
  header form still reaches the handler on the same endpoint.

Parent: PLAN-643 (OSS Security Hardening).
2026-04-21 22:22:06 -04:00
xarmian c2b67f5a9d fix(server): gate cloud admin endpoints via requireCloudMode (TASK-655) (#182)
* fix(server): gate cloud admin endpoints via requireCloudMode (TASK-655)

middleware_auth.go:184-189 and middleware_csrf.go:44-48 permanently
exempted /api/v1/admin/plan, /admin/stripe-customer-id, and
/admin/user-by-customer from RequireAuth and CSRFProtect — by path, not
by credential. In self-host mode these endpoints still responded to
every anonymous network caller (with "Cloud mode not configured"),
confirming their existence and telegraphing that the auth surface was
non-standard.

Three tightly-coupled changes:

1. Narrow both carve-outs from path-based to credential-based. The new
   isCloudSecretAuthAttempt(r) helper checks for X-Cloud-Secret header
   or legacy ?cloud_secret query-param; only requests that present one
   bypass auth/CSRF. Cookie-based admin callers continue through the
   normal session + CSRF gate.

2. Wrap the three endpoints in a dedicated requireCloudMode group.
   Self-host mode → 404, no endpoint-existence disclosure.

3. Admin callers via cookie now properly require CSRF for these
   endpoints (they previously bypassed), bringing them in line with
   every other /admin/* endpoint.

Tests (cloud_admin_gate_test.go):
- TestCloudAdminGate_SelfHost_Returns404 — anon + X-Cloud-Secret in
  self-host → 404 (requireCloudMode fires).
- TestCloudAdminGate_NoCloudSecret_RequiresAuth — cloud mode + no
  secret → 401 from auth gate (not the old "Cloud mode not configured").
- TestCloudAdminGate_ValidCloudSecret_PassesAuthAndCSRF — sidecar
  with matching X-Cloud-Secret reaches the handler; neither 401 nor
  403.
- TestCloudAdminGate_QueryParamSecret_BackwardCompat — legacy
  ?cloud_secret= on GET still works (TASK-656 removes this next).

Parent: PLAN-643 (OSS Security Hardening).

* fix(server): scope cloud-secret auth bypass to cloud admin paths per Codex P0

Codex caught a regression in the first cut: isCloudSecretAuthAttempt(r)
only checked for the presence of X-Cloud-Secret/?cloud_secret, so
setting either header on ANY path (e.g. GET /api/v1/workspaces) would
bypass RequireAuth globally. An anonymous attacker could list or
create workspaces just by adding one of those markers.

Add a cloudAdminPaths whitelist and require the request path to be one
of the three cloud admin endpoints before honoring the bypass. Defined
as a map so a future /api/v1/... route can't accidentally inherit it.

Regression test TestCloudAdminGate_BypassScopedToCloudPaths:
- GET /workspaces + X-Cloud-Secret → 401 (not bypass)
- GET /workspaces?cloud_secret=x → 401 (not bypass)
- POST /workspaces + X-Cloud-Secret → 4xx (CSRF 403 or auth 401)

* fix(server): make cloud-secret path gate visible at call sites

Codex re-flagged the path scoping on PR #182 — even after the fix, the
helper name 'isCloudSecretAuthAttempt' made the path scoping invisible
at the call site. Split into two primitives:
 - isCloudAdminPath(path) — path whitelist check
 - hasCloudSecretMarker(r)  — header/query marker check

Both middleware now combine them explicitly:
  if isCloudAdminPath(path) && hasCloudSecretMarker(r) { ... }

Behaviorally identical to the previous fix — tests still show
GET /workspaces with X-Cloud-Secret returning 401, POST /workspaces
with X-Cloud-Secret returning 403. Just makes the invariant readable
in RequireAuth and CSRFProtect without having to jump to the helper.

* fix(server): preserve body-cloud_secret auth for sidecar POSTs per Codex P1

Codex caught that POST sidecar calls carrying cloud_secret only in the
JSON body (the current pad-cloud sidecar behavior) would fail at
RequireAuth/CSRFProtect after this PR — handler-level validation never
runs. Breaking deployed sidecars isn't the intent of TASK-655; TASK-656
deprecates body+query cloud_secret in favor of X-Cloud-Secret header
exclusively, but that's a separate migration.

Add body peek to hasCloudSecretMarker for POST/PUT requests with
application/json content-type:
 - Read up to 64 KB of r.Body into a buffer.
 - Replace r.Body with an io.NopCloser wrapping the buffer so
   downstream handlers can still decode the JSON.
 - Return true if the parsed body has a non-empty cloud_secret field.

Parse errors and missing fields → false (request falls through to the
normal auth rejection, no permissiveness). The peek only runs when
the caller is already hitting a cloud admin path via the explicit
isCloudAdminPath() gate at the call sites, so the body-read cost is
bounded to three endpoints.

Test: TestCloudAdminGate_BodySecret_BackwardCompat posts with
cloud_secret in the JSON body and no X-Cloud-Secret header, asserts
the request reaches the handler (404 from unknown user_id, not
401/403 from middleware).
2026-04-21 22:15:52 -04:00