Harden API auth, SSO/RBAC identity, CSRF/lockout, tenant isolation, and input bounds (#5079)

Hardens Pulse API authentication, RBAC, SSO principal identity,
session/CSRF/lockout defenses, multi-tenant organization isolation,
action lifecycle authority, and request/metric memory bounds:

- Require admin + `settings:write` authentication (rejecting setup
tokens) on `/api/system/ssh-config` and
`/api/system/verify-temperature-ssh` and strictly validate SSH config
directive values against command injection.
- Harden SSO principal identity and group-to-role mapping lifecycle
(non-breaking issuer binding via `ProviderIssuerRegistry`, legacy
display-name migration guard, verified-email requirement for OIDC
domain/email restrictions, and role revocation when mappings change or
are removed).
- Enforce RBAC, admin, token-scope, and billing-state authority across
RBAC management routes, loopback trust in hosted mode, logout race
protection in `ensureAdminSession`, mobile token revocation on org-admin
removal, alerting/operator-state mutations, and entitlement refresh
token disclosure.
- Harden CSRF form fallback and fake-cookie storage, account lockout and
unauthenticated bcrypt paths, admin session invalidation on credential
rotation, and live credential revalidation on stalled request bodies.
- Enforce multi-tenant organization isolation and limits (org creation
caps, token cleanup on org deletion, public signup on tenant runtimes,
maintenance verification scoping, and tenant monitor lock contention).
- Harden action authority, cross-org action result isolation, live
credential checks on execution, and bound HTTP metrics label
cardinality, JSON request bodies, handoff/return JWT sizes, TrueNAS
topology RPC reads, suppression reasons, and download limits.
This commit is contained in:
rcourtman
2026-11-24 16:05:01 +00:00
committed by GitHub
148 changed files with 7308 additions and 702 deletions
+1 -1
View File
@@ -135,7 +135,7 @@ func TestServer_ActionDisclosureThroughRealAgentHandlers(t *testing.T) {
case <-ctx.Done():
t.Fatal("MCP stream never subscribed")
}
b.PublishActionCompletedRecord(record)
b.PublishActionCompletedRecord("default", record)
select {
case <-out.received:
case <-ctx.Done():
+32 -8
View File
@@ -491,6 +491,15 @@ request path. Do not substitute a display name or a Proxmox VM number.
| `PUT /api/resources/{id}/operator-state` | `monitoring:write` | Replaces the entire state and returns the saved record. |
| `DELETE /api/resources/{id}/operator-state` | `monitoring:write` | Removes the entire state, returning HTTP 204 even if it was already absent. |
Scopes apply to API tokens. A signed-in browser or proxy user needs the same
authority as reviewing actions (an administrator, or an explicit action approval
grant) to change `neverAutoRemediate`, `lifecycleState` or
`autoRemediationPolicy`, because Pulse obeys them when it approves and runs
actions. Without it, a `PUT` must carry those three settings as saved, and a
`DELETE` is refused with HTTP 403 while any of them differs from the default.
Monitoring mode, maintenance windows, criticality and notes stay open to every
signed-in user, as does reading.
**PUT replaces the whole record, not just the fields supplied.** Read the current
state first and preserve unrelated settings, such as monitoring mode, lifecycle,
remediation policy, criticality and notes. Treat only `operator_state_not_set`
@@ -1200,6 +1209,14 @@ Common reporting error codes:
Alert configuration and history (requires `monitoring:read`/`monitoring:write`).
Scopes apply to API tokens. In a browser or proxy session, every signed-in user
can read these routes and acknowledge, snooze or clear single alerts. Saving
the alert configuration, the intent policies or the external watchdog,
activating delivery and deleting alert history also need an administrator, with
multiple organizations a manager of the organization, or, where RBAC roles are
enforced, a role that grants `write` on `alerts` such as the built-in `operator`
(`403` otherwise).
For planned downtime, use [Resource Maintenance and Operator State](#resource-maintenance-and-operator-state).
For an existing incident whose notifications should be paused without clearing
it, use the snooze and unsnooze endpoints below.
@@ -1470,11 +1487,11 @@ Enable or disable mock data generation (dev/demo only).
### SSH Config (Temperature Monitoring)
`POST /api/system/ssh-config`
Writes the SSH config used for temperature collection (requires setup token or auth).
Writes the SSH config used for temperature collection. Requires admin + `settings:write`. Setup tokens are not accepted. Only `Host`, `HostName`, `ProxyJump`, `User`, `IdentityFile` and `StrictHostKeyChecking` are allowed, with plain host, user and path values.
### Verify Temperature SSH
`POST /api/system/verify-temperature-ssh`
Tests SSH connectivity for temperature collection (requires setup token or auth).
Tests SSH connectivity for temperature collection. Requires admin + `settings:write`. Setup tokens are not accepted.
### Scheduler Health
`GET /api/monitoring/scheduler/health`
@@ -1542,6 +1559,11 @@ OIDC and SAML configuration is managed via SSO providers.
- `PUT /api/security/sso/providers/{id}` (admin, `settings:write`)
- `DELETE /api/security/sso/providers/{id}` (admin, `settings:write`)
A provider decides who can sign in and which roles its groups receive, so an
API token may create, update or delete one only if it has full-access scope
(`*`) and is not bound to a non-default organization. Any other token gets
`403`. Browser sessions are not limited this way.
Provider mutation request contract:
- Max request body: 1MB.
- Unknown JSON fields are ignored. A trailing payload after the JSON object is rejected with `invalid_json`.
@@ -1641,7 +1663,7 @@ Returns organizations accessible to the authenticated user.
```json
{ "id": "acme-corp", "displayName": "Acme Corporation" }
```
The creator becomes the owner and first member. Organization IDs use letters, digits, periods, underscores or hyphens, 1–64 characters, but cannot be `.` or `..`. Prefer a simple lowercase/hyphen ID such as the example.
The creator becomes the owner and first member. A user who is not an instance administrator can own at most 20 organizations. Past that the request returns `409` with `organization_limit_reached`. Organization IDs use letters, digits, periods, underscores or hyphens, 1–64 characters, but cannot be `.` or `..`. Prefer a simple lowercase/hyphen ID such as the example.
### Get Organization
`GET /api/orgs/{id}` (requires `settings:read`)
@@ -1667,7 +1689,7 @@ Returns all members with their roles. User must be a member of the org.
```json
{ "userId": "jane", "role": "editor" }
```
Roles: `owner`, `admin`, `editor`, `viewer`. Admin or owner role required. A new user receives a pending invitation (`202`) and must accept it in Pulse before gaining membership. Posting an existing member's `userId` updates their role; there is no member PATCH endpoint. Setting role to `owner` transfers ownership only to an existing member, by the current owner after fresh sign-in. Default org members cannot be managed.
Roles: `owner`, `admin`, `editor`, `viewer`. Admin or owner role required. A new user receives a pending invitation (`202`) and must accept it in Pulse before gaining membership. Posting an existing member's `userId` updates their role. There is no member PATCH endpoint. Setting role to `owner` transfers ownership only to an existing member, by the current owner after fresh sign-in. Unless either is an instance administrator, a new owner who already owns 20 organizations is refused with `409` `organization_limit_reached`. Default org members cannot be managed.
### Remove Member
`DELETE /api/orgs/{id}/members/{userId}` (requires `settings:write`, session auth only)
@@ -1812,6 +1834,7 @@ Runs a focused investigation for an alert payload (used by the UI).
- `POST /api/ai/patrol/attention/{id}/unacknowledge`
- `POST /api/ai/patrol/attention/{id}/suppress`
- Body: `{ "reason": "...", "expiresAt": "<RFC3339>" }`.
- The reason is required and is at most 240 characters.
- The expiry must be in the future and no more than 30 days away.
- `POST /api/ai/patrol/attention/{id}/unsuppress`
- `POST /api/ai/patrol/attention/{id}/actions/restart/plan`
@@ -1829,7 +1852,7 @@ Runs a focused investigation for an alert payload (used by the UI).
- `PUT /api/ai/patrol/autonomy`
- `GET /api/ai/patrol/status`
- `GET /api/ai/patrol/findings`
- `DELETE /api/ai/patrol/findings` (clear all findings)
- `DELETE /api/ai/patrol/findings` (clear all findings, in a session an administrator or organization manager)
- `GET /api/ai/patrol/objectives`
- `POST /api/ai/patrol/objectives`
- `GET /api/ai/patrol/objectives/{id}`
@@ -1876,10 +1899,11 @@ Runs a focused investigation for an alert payload (used by the UI).
- `POST /api/ai/patrol/findings/note` (`ai:execute`, and permission to execute actions: Patrol reads the note)
- `POST /api/ai/patrol/resolve` (optional `resolution_note` requires permission to execute actions)
- `POST /api/ai/patrol/snooze` (`ai:execute`)
- `POST /api/ai/patrol/suppress` (`ai:execute`)
- `POST /api/ai/patrol/suppress` (`ai:execute`, in a session an administrator or organization manager)
- `GET /api/ai/patrol/suppressions` (`ai:execute`)
- `POST /api/ai/patrol/suppressions` (`ai:execute`)
- `DELETE /api/ai/patrol/suppressions/{id}` (`ai:execute`)
- `POST /api/ai/patrol/suppressions` (`ai:execute`, in a session an administrator or organization manager)
- `DELETE /api/ai/patrol/suppressions/{id}` (`ai:execute`, in a session an administrator or organization
manager, except a `finding_` row, which reopens a dismissed finding)
- `GET /api/ai/patrol/dismissed` (`ai:execute`)
Patrol itself and managing its findings (acknowledge, snooze, suppress,
+4 -1
View File
@@ -100,7 +100,10 @@ signed-in UI with its session and CSRF protection.
{"id": "production-datacenter", "displayName": "Production Datacenter"}
```
The creator becomes the owner. `id` is a stable ID of 1–64 characters using
The creator becomes the owner. A user who is not an instance administrator
can own at most 20 organizations: past that, creating one, or being handed one
by another such user, returns `409` with `organization_limit_reached`.
`id` is a stable ID of 1–64 characters using
letters, digits, periods, underscores or hyphens, but not `.` or `..`; use a
simple lowercase/hyphen ID such as the example. `displayName` is the name
shown in Pulse. `name` and `description` are not the creation fields.
+2
View File
@@ -76,6 +76,8 @@ At sign-in, every non-empty list must match. Entries within one list are alterna
> [Check admin access in a separate browser session](#-quick-start) and keep
> your independent administrator login even after SSO works.
An address the IdP reports as unverified (`email_verified: false`) matches neither **Allowed Domains** nor **Allowed Emails**. Sign-in fails with `email_unverified` until the user verifies it at the IdP. An IdP that omits `email_verified` is not affected.
### Group-to-Role Mapping
Automatically assign Pulse roles based on OIDC group membership. When a user logs in, Pulse checks their groups claim and assigns the corresponding roles. Mapping groups to the built-in `admin`, `operator`, and `viewer` roles is included with Community SSO. Creating custom roles and manually managing user assignments remain Pro RBAC features.
+3 -3
View File
@@ -32,9 +32,9 @@ existing work to `stale`; permission or provider uncertainty moves it to
detector evidence can confirm recovery.
Acknowledgement is reversible and does not reduce the active issue truth.
Suppression requires a non-empty reason and an expiry no more than 30 days in
the future. The Patrol UI offers shorter 1-hour, 24-hour, and 7-day choices by
default.
Suppression requires a non-empty reason of at most 240 characters and an expiry
no more than 30 days in the future. The Patrol UI offers shorter 1-hour,
24-hour, and 7-day choices by default.
## Evidence
+2
View File
@@ -29,6 +29,8 @@ In Docker and Kubernetes you must expose `9091` explicitly if you want to scrape
| `pulse_http_requests_total` | Counter | Total requests by `method`, `route`, `status`. |
| `pulse_http_request_errors_total` | Counter | Error totals by `method`, `route`, `status_class` (`client_error`, `server_error`, `none`). |
`route` is the registered route pattern that serves the request (for example `/api/state` or `/api/orgs/{id}`), not the requested path. Requests that match no pattern, including frontend pages and assets, are recorded as `unmatched`. `method` is a standard HTTP method or `other`.
## 🔄 Polling & Nodes
| Metric | Type | Description |
@@ -110,9 +110,17 @@ principal once a stable user ID exists.
should be canonicalized to stable user IDs when the stable ID is known.
7. Self-hosted OIDC and SAML sessions bind to an opaque principal derived from
provider type, provider ID, and the provider subject (`sub` or `NameID`).
RBAC may copy a legacy username/email assignment to that principal during
compatibility migration, but the browser session and tracked active-session
owner must be the stable SSO principal.
The subject is identity exactly as the provider asserted it: a blank or
whitespace-padded subject is refused at sign-in, never trimmed onto the
principal of another account. Each provider entry ID binds its original
issuer so pointing or recreating an entry against a different issuer yields
issuer-scoped principals without renaming existing users on the original
issuer. RBAC may copy a legacy username/email assignment to that principal
during compatibility migration, but the browser session and tracked
active-session owner must be the stable SSO principal. Migration candidates
are claim text the signing-in user may control: a candidate in the stable
`sso:` principal namespace names a current identity, not a legacy alias, and
must never select that principal's assignment.
## Current Explicit Exception
@@ -10394,6 +10394,9 @@ agent tokens, command sessions, and report identity. Deprovisioning a human
principal revokes that principal's browser sessions only and does not delete,
reassign, or synthesize agent lifecycle state. The api-contracts and
security-privacy contracts own the authoritative behavior and proof.
The same separation holds when SSO login withdraws roles that a removed group
role mapping had saved: only the human principal's role list changes, and no
agent token, enrollment, command session, or report identity is touched.
### Resource monitoring policy does not mutate agent lifecycle
@@ -3995,7 +3995,7 @@ a new API state machine, queue contract, or verification-accounting field.
sqlite stores (handoff JTI, purchase-return redemptions) open through
`openHardenedSecretsDB` so the private-permission hardening policy stays
single-sourced; privileged settings endpoints gate through
`serveSetupTokenOrSettingsWrite` in `internal/api/router.go`; patrol
`serveSettingsWrite` in `internal/api/router.go`; patrol
findings convert to the unified store through one `unifiedFindingFromAI`.
1. Add or change payload fields through handler + contract tests together
2. Update frontend API types in lockstep with backend contract changes.
@@ -8852,7 +8852,12 @@ That same runtime SSO contract also owns browser-session principal identity:
OIDC/SAML session users from provider-scoped stable subjects (`sub`/`NameID`
plus provider ID), not mutable username, email, or display-name claims. Legacy
username/email RBAC assignments may be copied only as compatibility migration
inputs when no authoritative group mapping is present. Successful OIDC/SAML
inputs when no authoritative group mapping is present. Roles written by an
authoritative group mapping are saved with that origin (`rolesFromMapping` on
RBAC user-assignment reads). The first login after the provider stops mapping
groups must withdraw them before legacy or manual assignments are considered.
Roles saved through `PUT /api/admin/users/{username}/roles` clear the origin
and are kept. Successful OIDC/SAML
login may upsert bounded `displayName`, `email`, `providerType`, `providerId`,
and `lastLoginAt` presentation metadata against that stable principal; these
fields are returned by RBAC user-assignment reads but never become session or
@@ -4129,7 +4129,14 @@ assignments, writes the acting administrator to the RBAC changelog, rejects
self-removal, and revokes every persisted session and matching CSRF record for
that principal, including sessions restored after restart. Deprovisioning is
not an IdP denylist: a later login that still passes provider restrictions may
recreate the identity. Enterprise regression coverage in
recreate the identity. The identity table also records whether a principal's
current role list was written by an SSO group role mapping
(`roles_from_mapping`, set only through `MappedRoleManager`). A mapped grant
must not outlive its mapping: once the provider has no group role mappings,
the principal's next login withdraws roles carrying that origin, while roles
saved by an administrator or break-glass recovery clear the origin and are
preserved. Rows that predate the column carry no origin until the next mapped
login. Enterprise regression coverage in
`pulse-enterprise/internal/rbac/rbac_test.go` must preserve the real startup
order and prove that an OIDC principal assigned after initialization is
authorized from the canonical manager.
@@ -8699,6 +8699,11 @@ restore, retention, resource-store, or recovery evidence. Additive RBAC schema
upgrade preserves older identities and fails construction on migration errors;
the security-privacy and api-contracts contracts own the authoritative shape
and proof.
The additive `roles_from_mapping` column follows the same upgrade rule. It
defaults to zero for older identities, so upgrade withdraws no saved role, and
it marks role lists written by an SSO group role mapping for withdrawal at
login once that mapping is removed. No backup, restore, retention, or recovery
state reads or writes it.
### Resource monitoring lifecycle preserves recovery evidence
+32 -8
View File
@@ -491,6 +491,15 @@ request path. Do not substitute a display name or a Proxmox VM number.
| `PUT /api/resources/{id}/operator-state` | `monitoring:write` | Replaces the entire state and returns the saved record. |
| `DELETE /api/resources/{id}/operator-state` | `monitoring:write` | Removes the entire state, returning HTTP 204 even if it was already absent. |
Scopes apply to API tokens. A signed-in browser or proxy user needs the same
authority as reviewing actions (an administrator, or an explicit action approval
grant) to change `neverAutoRemediate`, `lifecycleState` or
`autoRemediationPolicy`, because Pulse obeys them when it approves and runs
actions. Without it, a `PUT` must carry those three settings as saved, and a
`DELETE` is refused with HTTP 403 while any of them differs from the default.
Monitoring mode, maintenance windows, criticality and notes stay open to every
signed-in user, as does reading.
**PUT replaces the whole record, not just the fields supplied.** Read the current
state first and preserve unrelated settings, such as monitoring mode, lifecycle,
remediation policy, criticality and notes. Treat only `operator_state_not_set`
@@ -1200,6 +1209,14 @@ Common reporting error codes:
Alert configuration and history (requires `monitoring:read`/`monitoring:write`).
Scopes apply to API tokens. In a browser or proxy session, every signed-in user
can read these routes and acknowledge, snooze or clear single alerts. Saving
the alert configuration, the intent policies or the external watchdog,
activating delivery and deleting alert history also need an administrator, with
multiple organizations a manager of the organization, or, where RBAC roles are
enforced, a role that grants `write` on `alerts` such as the built-in `operator`
(`403` otherwise).
For planned downtime, use [Resource Maintenance and Operator State](#resource-maintenance-and-operator-state).
For an existing incident whose notifications should be paused without clearing
it, use the snooze and unsnooze endpoints below.
@@ -1470,11 +1487,11 @@ Enable or disable mock data generation (dev/demo only).
### SSH Config (Temperature Monitoring)
`POST /api/system/ssh-config`
Writes the SSH config used for temperature collection (requires setup token or auth).
Writes the SSH config used for temperature collection. Requires admin + `settings:write`. Setup tokens are not accepted. Only `Host`, `HostName`, `ProxyJump`, `User`, `IdentityFile` and `StrictHostKeyChecking` are allowed, with plain host, user and path values.
### Verify Temperature SSH
`POST /api/system/verify-temperature-ssh`
Tests SSH connectivity for temperature collection (requires setup token or auth).
Tests SSH connectivity for temperature collection. Requires admin + `settings:write`. Setup tokens are not accepted.
### Scheduler Health
`GET /api/monitoring/scheduler/health`
@@ -1542,6 +1559,11 @@ OIDC and SAML configuration is managed via SSO providers.
- `PUT /api/security/sso/providers/{id}` (admin, `settings:write`)
- `DELETE /api/security/sso/providers/{id}` (admin, `settings:write`)
A provider decides who can sign in and which roles its groups receive, so an
API token may create, update or delete one only if it has full-access scope
(`*`) and is not bound to a non-default organization. Any other token gets
`403`. Browser sessions are not limited this way.
Provider mutation request contract:
- Max request body: 1MB.
- Unknown JSON fields are ignored. A trailing payload after the JSON object is rejected with `invalid_json`.
@@ -1641,7 +1663,7 @@ Returns organizations accessible to the authenticated user.
```json
{ "id": "acme-corp", "displayName": "Acme Corporation" }
```
The creator becomes the owner and first member. Organization IDs use letters, digits, periods, underscores or hyphens, 1–64 characters, but cannot be `.` or `..`. Prefer a simple lowercase/hyphen ID such as the example.
The creator becomes the owner and first member. A user who is not an instance administrator can own at most 20 organizations. Past that the request returns `409` with `organization_limit_reached`. Organization IDs use letters, digits, periods, underscores or hyphens, 1–64 characters, but cannot be `.` or `..`. Prefer a simple lowercase/hyphen ID such as the example.
### Get Organization
`GET /api/orgs/{id}` (requires `settings:read`)
@@ -1667,7 +1689,7 @@ Returns all members with their roles. User must be a member of the org.
```json
{ "userId": "jane", "role": "editor" }
```
Roles: `owner`, `admin`, `editor`, `viewer`. Admin or owner role required. A new user receives a pending invitation (`202`) and must accept it in Pulse before gaining membership. Posting an existing member's `userId` updates their role; there is no member PATCH endpoint. Setting role to `owner` transfers ownership only to an existing member, by the current owner after fresh sign-in. Default org members cannot be managed.
Roles: `owner`, `admin`, `editor`, `viewer`. Admin or owner role required. A new user receives a pending invitation (`202`) and must accept it in Pulse before gaining membership. Posting an existing member's `userId` updates their role. There is no member PATCH endpoint. Setting role to `owner` transfers ownership only to an existing member, by the current owner after fresh sign-in. Unless either is an instance administrator, a new owner who already owns 20 organizations is refused with `409` `organization_limit_reached`. Default org members cannot be managed.
### Remove Member
`DELETE /api/orgs/{id}/members/{userId}` (requires `settings:write`, session auth only)
@@ -1812,6 +1834,7 @@ Runs a focused investigation for an alert payload (used by the UI).
- `POST /api/ai/patrol/attention/{id}/unacknowledge`
- `POST /api/ai/patrol/attention/{id}/suppress`
- Body: `{ "reason": "...", "expiresAt": "<RFC3339>" }`.
- The reason is required and is at most 240 characters.
- The expiry must be in the future and no more than 30 days away.
- `POST /api/ai/patrol/attention/{id}/unsuppress`
- `POST /api/ai/patrol/attention/{id}/actions/restart/plan`
@@ -1829,7 +1852,7 @@ Runs a focused investigation for an alert payload (used by the UI).
- `PUT /api/ai/patrol/autonomy`
- `GET /api/ai/patrol/status`
- `GET /api/ai/patrol/findings`
- `DELETE /api/ai/patrol/findings` (clear all findings)
- `DELETE /api/ai/patrol/findings` (clear all findings, in a session an administrator or organization manager)
- `GET /api/ai/patrol/objectives`
- `POST /api/ai/patrol/objectives`
- `GET /api/ai/patrol/objectives/{id}`
@@ -1876,10 +1899,11 @@ Runs a focused investigation for an alert payload (used by the UI).
- `POST /api/ai/patrol/findings/note` (`ai:execute`, and permission to execute actions: Patrol reads the note)
- `POST /api/ai/patrol/resolve` (optional `resolution_note` requires permission to execute actions)
- `POST /api/ai/patrol/snooze` (`ai:execute`)
- `POST /api/ai/patrol/suppress` (`ai:execute`)
- `POST /api/ai/patrol/suppress` (`ai:execute`, in a session an administrator or organization manager)
- `GET /api/ai/patrol/suppressions` (`ai:execute`)
- `POST /api/ai/patrol/suppressions` (`ai:execute`)
- `DELETE /api/ai/patrol/suppressions/{id}` (`ai:execute`)
- `POST /api/ai/patrol/suppressions` (`ai:execute`, in a session an administrator or organization manager)
- `DELETE /api/ai/patrol/suppressions/{id}` (`ai:execute`, in a session an administrator or organization
manager, except a `finding_` row, which reopens a dismissed finding)
- `GET /api/ai/patrol/dismissed` (`ai:execute`)
Patrol itself and managing its findings (acknowledge, snooze, suppress,
+4 -1
View File
@@ -100,7 +100,10 @@ signed-in UI with its session and CSRF protection.
{"id": "production-datacenter", "displayName": "Production Datacenter"}
```
The creator becomes the owner. `id` is a stable ID of 1–64 characters using
The creator becomes the owner. A user who is not an instance administrator
can own at most 20 organizations: past that, creating one, or being handed one
by another such user, returns `409` with `organization_limit_reached`.
`id` is a stable ID of 1–64 characters using
letters, digits, periods, underscores or hyphens, but not `.` or `..`; use a
simple lowercase/hyphen ID such as the example. `displayName` is the name
shown in Pulse. `name` and `description` are not the creation fields.
+2
View File
@@ -76,6 +76,8 @@ At sign-in, every non-empty list must match. Entries within one list are alterna
> [Check admin access in a separate browser session](#-quick-start) and keep
> your independent administrator login even after SSO works.
An address the IdP reports as unverified (`email_verified: false`) matches neither **Allowed Domains** nor **Allowed Emails**. Sign-in fails with `email_unverified` until the user verifies it at the IdP. An IdP that omits `email_verified` is not affected.
### Group-to-Role Mapping
Automatically assign Pulse roles based on OIDC group membership. When a user logs in, Pulse checks their groups claim and assigns the corresponding roles. Mapping groups to the built-in `admin`, `operator`, and `viewer` roles is included with Community SSO. Creating custom roles and manually managing user assignments remain Pro RBAC features.
@@ -32,9 +32,9 @@ existing work to `stale`; permission or provider uncertainty moves it to
detector evidence can confirm recovery.
Acknowledgement is reversible and does not reduce the active issue truth.
Suppression requires a non-empty reason and an expiry no more than 30 days in
the future. The Patrol UI offers shorter 1-hour, 24-hour, and 7-day choices by
default.
Suppression requires a non-empty reason of at most 240 characters and an expiry
no more than 30 days in the future. The Patrol UI offers shorter 1-hour,
24-hour, and 7-day choices by default.
## Evidence
+91 -35
View File
@@ -148,10 +148,12 @@ type Service struct {
LiveCheckAuthorizer LiveCheckAuthorizer
StepUpVerifier StepUpVerifier
RefreshPlanner RefreshPlanner
// OnActionCompleted receives every terminal (completed/failed) audit
// record, including refused-before-dispatch failures, so SSE bridges
// and reconcilers observe the full lifecycle regardless of transport.
OnActionCompleted func(unified.ActionAuditRecord)
// OnActionCompleted receives the org ID and every terminal
// (completed/failed) audit record, including refused-before-dispatch
// failures, so SSE bridges and reconcilers observe the full lifecycle
// regardless of transport. The org ID scopes the resulting agent event
// to the organization whose store holds the action.
OnActionCompleted func(orgID string, record unified.ActionAuditRecord)
// OnActionTransition receives the org ID and audit record after every
// successfully persisted state transition: plan creation, approval
// decisions, and terminal execution outcomes (including refusals).
@@ -997,6 +999,11 @@ func (s *Service) Decide(ctx context.Context, orgID, actionID string, decision u
if err := s.validateCurrentReadiness(ctx, orgID, record, liveCheck); err != nil {
return unified.ActionAuditRecord{}, err
}
// The agent's answer can outlive the reviewer's authority. Ask again
// before the approval is persisted.
if err := s.DecisionAuthorizer.AuthorizeDecision(ctx, orgID, record, decision); err != nil {
return unified.ActionAuditRecord{}, err
}
}
if err := s.validateApprovalFloor(ctx, record, decision, true); err != nil {
return unified.ActionAuditRecord{}, err
@@ -1048,6 +1055,9 @@ func (s *Service) Decide(ctx context.Context, orgID, actionID string, decision u
if err := s.validateCurrentReadiness(ctx, orgID, current, liveCheck); err != nil {
return unified.ActionAuditRecord{}, err
}
if err := s.DecisionAuthorizer.AuthorizeDecision(ctx, orgID, current, decision); err != nil {
return unified.ActionAuditRecord{}, err
}
}
if err := s.validateApprovalFloor(ctx, current, decision, false); err != nil {
return unified.ActionAuditRecord{}, err
@@ -1308,43 +1318,74 @@ func (s *Service) validateApprovalFloor(ctx context.Context, record unified.Acti
// linearization point against an operator policy save: a lock saved before it
// refuses the dispatch, a lock saved after it queues behind it and does not
// recall a dispatch that is already admitted.
//
// A call that dispatches nothing (the action is already final, or another
// caller holds its dispatch) replays the stored record only to an actor who
// may also review the action. Execute authority alone gets
// ErrActionExecutionFinal or ErrActionAlreadyExecuting, so the record of an
// action the caller did not run is never the answer to running it again.
func (s *Service) Execute(ctx context.Context, orgID, actionID string, actor unified.ActionActor, reason string) (unified.ActionAuditRecord, error) {
record, dispatched, err := s.execute(ctx, orgID, actionID, actor, reason)
if err != nil || dispatched || s.recordReplayAllowed(ctx, orgID, record, actor) {
return record, err
}
if record.State == unified.ActionStateExecuting {
return unified.ActionAuditRecord{}, unified.ErrActionAlreadyExecuting
}
return unified.ActionAuditRecord{}, unified.ErrActionExecutionFinal
}
// recordReplayAllowed reports whether actor may be handed the stored record of
// an action this call did not dispatch. That is a read of what others planned,
// approved and ran, so it takes the review authority the DecisionAuthorizer
// holds, the same one the transports ask for before showing an action. It
// fails closed.
func (s *Service) recordReplayAllowed(ctx context.Context, orgID string, record unified.ActionAuditRecord, actor unified.ActionActor) bool {
if s.DecisionAuthorizer == nil {
return false
}
return s.DecisionAuthorizer.AuthorizeDecision(ctx, orgID, record, unified.ActionDecision{Actor: unified.NormalizeActionActor(actor)}) == nil
}
// execute is Execute before the replay rule. The bool reports whether this
// call handed the action to the executor.
func (s *Service) execute(ctx context.Context, orgID, actionID string, actor unified.ActionActor, reason string) (unified.ActionAuditRecord, bool, error) {
actionID = strings.TrimSpace(actionID)
if actionID == "" {
return unified.ActionAuditRecord{}, &ActionNotFoundError{ActionID: actionID}
return unified.ActionAuditRecord{}, false, &ActionNotFoundError{ActionID: actionID}
}
store, err := s.store(orgID)
if err != nil {
return unified.ActionAuditRecord{}, err
return unified.ActionAuditRecord{}, false, err
}
record, ok, err := store.GetActionAudit(actionID)
if err != nil {
return unified.ActionAuditRecord{}, &QueryError{Op: "action audit", Err: err}
return unified.ActionAuditRecord{}, false, &QueryError{Op: "action audit", Err: err}
}
if !ok {
return unified.ActionAuditRecord{}, &ActionNotFoundError{ActionID: actionID}
return unified.ActionAuditRecord{}, false, &ActionNotFoundError{ActionID: actionID}
}
actor = unified.NormalizeActionActor(actor)
if err := unified.ValidateActionActor(actor); err != nil ||
(actor.Kind != unified.ActionActorUser && actor.Kind != unified.ActionActorAPIToken) ||
actor.OrgID != strings.TrimSpace(orgID) {
return unified.ActionAuditRecord{}, ErrApprovalActorNotHuman
return unified.ActionAuditRecord{}, false, ErrApprovalActorNotHuman
}
if err := unified.ValidateHumanActionBinding(record, orgID); err != nil {
return unified.ActionAuditRecord{}, err
return unified.ActionAuditRecord{}, false, err
}
if s.ExecutionAuthorizer == nil {
return unified.ActionAuditRecord{}, ErrExecutionAuthorizationUnavailable
return unified.ActionAuditRecord{}, false, ErrExecutionAuthorizationUnavailable
}
if err := s.ExecutionAuthorizer.AuthorizeExecution(ctx, orgID, record, actor); err != nil {
return unified.ActionAuditRecord{}, err
return unified.ActionAuditRecord{}, false, err
}
actorID := actor.SubjectID
if record.State == unified.ActionStateExecuting {
return s.dispatchCommitted(ctx, orgID, store, record, actorID)
}
if record.State == unified.ActionStateCompleted || record.State == unified.ActionStateFailed {
return record, nil
return record, false, nil
}
// Human admission shares the automatic path's boundary: the operator
@@ -1355,10 +1396,10 @@ func (s *Service) Execute(ctx context.Context, orgID, actionID string, actor uni
// is released before the executor runs.
coordinator := s.admissionCoordinator()
coordinator.mu.RLock()
started, admitted, admissionErr := s.beginHumanExecution(ctx, orgID, store, record, actorID, reason)
started, admitted, admissionErr := s.beginHumanExecution(ctx, orgID, store, record, actor, reason)
coordinator.mu.RUnlock()
if !admitted {
return started, admissionErr
return started, false, admissionErr
}
return s.dispatchCommitted(ctx, orgID, store, started, actorID)
}
@@ -1368,7 +1409,8 @@ func (s *Service) Execute(ctx context.Context, orgID, actionID string, actor uni
// admission read lock. A true result means the action is executing and its
// durable dispatch attempt may be driven, including when a concurrent caller
// won the admission.
func (s *Service) beginHumanExecution(ctx context.Context, orgID string, store Store, record unified.ActionAuditRecord, actorID, reason string) (unified.ActionAuditRecord, bool, error) {
func (s *Service) beginHumanExecution(ctx context.Context, orgID string, store Store, record unified.ActionAuditRecord, actor unified.ActionActor, reason string) (unified.ActionAuditRecord, bool, error) {
actorID := actor.SubjectID
now := s.now()
record, err := s.materializeExpiry(store, orgID, record)
if err != nil {
@@ -1384,7 +1426,7 @@ func (s *Service) beginHumanExecution(ctx context.Context, orgID string, store S
return unified.ActionAuditRecord{}, false, &PersistError{Op: "refused action execution", Err: persistErr}
}
s.publishTransition(orgID, failed)
s.publishCompleted(failed)
s.publishCompleted(orgID, failed)
return failed, false, err
}
return unified.ActionAuditRecord{}, false, err
@@ -1400,11 +1442,18 @@ func (s *Service) beginHumanExecution(ctx context.Context, orgID string, store S
return unified.ActionAuditRecord{}, false, &PersistError{Op: "refused action execution", Err: persistErr}
}
s.publishTransition(orgID, failed)
s.publishCompleted(failed)
s.publishCompleted(orgID, failed)
return failed, false, err
}
return unified.ActionAuditRecord{}, false, err
}
// Waiting for the admission lock and for the agent's answer can outlive
// the caller's authority. Ask again at the commit, so a credential
// withdrawn during the wait does not start the dispatch. The action stays
// approved for a caller who may still run it.
if err := s.ExecutionAuthorizer.AuthorizeExecution(ctx, orgID, record, actor); err != nil {
return unified.ActionAuditRecord{}, false, err
}
started, startEvent, err := unified.BeginActionExecution(record, actorID, now)
if err != nil {
@@ -1447,7 +1496,8 @@ func (s *Service) ExecuteUnderPolicy(ctx context.Context, orgID, actionID, actor
if !admitted {
return started, admissionErr
}
return s.dispatchCommitted(ctx, orgID, store, started, actor)
completed, _, err := s.dispatchCommitted(ctx, orgID, store, started, actor)
return completed, err
}
func (s *Service) beginPolicyExecution(ctx context.Context, orgID, actionID, actor string, authorize PolicyAuthorizer) (unified.ActionAuditRecord, Store, bool, error) {
@@ -1581,45 +1631,51 @@ func (s *Service) materializeExpiry(store Store, orgID string, record unified.Ac
return expired, nil
}
func (s *Service) dispatchCommitted(ctx context.Context, orgID string, store Store, record unified.ActionAuditRecord, actor string) (unified.ActionAuditRecord, error) {
// dispatchCommitted drives the durable dispatch attempt of an executing action.
// The bool reports whether this call won the claim and handed the action to
// the executor. It is false when the attempt belongs to another caller: a
// legacy row, a lost claim, or the reconciliation of a dispatch already sent.
func (s *Service) dispatchCommitted(ctx context.Context, orgID string, store Store, record unified.ActionAuditRecord, actor string) (unified.ActionAuditRecord, bool, error) {
attempt, found, err := store.GetActionDispatchAttempt(record.ID)
if err != nil {
return unified.ActionAuditRecord{}, &QueryError{Op: "action dispatch attempt", Err: err}
return unified.ActionAuditRecord{}, false, &QueryError{Op: "action dispatch attempt", Err: err}
}
if !found {
// Legacy executing rows predate durable dispatch authority. They must
// remain observable, but can never be readmitted or blindly resent.
return record, nil
return record, false, nil
}
if attempt.State == unified.ActionDispatchReceiptPending || attempt.State == unified.ActionDispatchReceiptRecorded {
return s.reconcileCommitted(ctx, orgID, store, record, attempt, actor)
reconciled, err := s.reconcileCommitted(ctx, orgID, store, record, attempt, actor)
return reconciled, false, err
}
owner := fmt.Sprintf("action-lifecycle:%s:%d", attempt.ID, dispatchWorkerSequence.Add(1))
attempt, claimed, err := store.ClaimActionDispatch(record.ID, owner, s.now(), 30*time.Second)
if err != nil {
return unified.ActionAuditRecord{}, &PersistError{Op: "action dispatch claim", Err: err}
return unified.ActionAuditRecord{}, false, &PersistError{Op: "action dispatch claim", Err: err}
}
if !claimed {
return record, nil
return record, false, nil
}
attempt, err = store.MarkActionDispatchStarted(attempt.ID, owner, s.now())
if err != nil {
return unified.ActionAuditRecord{}, &PersistError{Op: "action dispatch start", Err: err}
return unified.ActionAuditRecord{}, false, &PersistError{Op: "action dispatch start", Err: err}
}
result, execErr := s.Executor.ExecuteAction(withDispatchAttempt(ctx, attempt), record)
if execErr != nil {
if result != nil {
return record, fmt.Errorf("%w: executor returned both result and error", unified.ErrExecutorResultContract)
return record, true, fmt.Errorf("%w: executor returned both result and error", unified.ErrExecutorResultContract)
}
// A timeout, disconnect, cancellation, or generic executor error is not
// proof that the transport answered. Preserve receipt_pending so a
// reconciler can query by attempt ID without resending.
return record, execErr
return record, true, execErr
}
receipt := unified.ActionDispatchReceipt{
AttemptID: attempt.ID, ActionID: record.ID, TransportRequestID: attempt.ID, ReceivedAt: s.now(),
}
return s.completeCorrelatedDispatch(orgID, store, record, receipt, result, actor)
completed, err := s.completeCorrelatedDispatch(orgID, store, record, receipt, result, actor)
return completed, true, err
}
func (s *Service) reconcileCommitted(ctx context.Context, orgID string, store Store, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt, actor string) (unified.ActionAuditRecord, error) {
@@ -1663,7 +1719,7 @@ func (s *Service) completeCorrelatedDispatch(orgID string, store Store, record u
return unified.ActionAuditRecord{}, &PersistError{Op: "correlated action dispatch completion", Err: err}
}
s.publishTransition(orgID, completed)
s.publishCompleted(completed)
s.publishCompleted(orgID, completed)
truth := unified.CanonicalActionResultV2(completed)
verificationOutcome := string(truth.Verification.Status)
if truth.Verification.Status == unified.ActionVerificationInconclusive &&
@@ -1759,7 +1815,7 @@ func (s *Service) ForceFail(orgID, actionID, actor, reason string) (unified.Acti
return unified.ActionAuditRecord{}, &PersistError{Op: "action force fail", Err: err}
}
s.publishTransition(orgID, failed)
s.publishCompleted(failed)
s.publishCompleted(orgID, failed)
return failed, nil
}
@@ -1777,7 +1833,7 @@ func (s *Service) RecoverExecutingActions(ctx context.Context, orgID, actor stri
}
recovered := make([]unified.ActionAuditRecord, 0, len(records))
for _, record := range records {
current, recoverErr := s.dispatchCommitted(ctx, orgID, store, record, actor)
current, _, recoverErr := s.dispatchCommitted(ctx, orgID, store, record, actor)
if recoverErr != nil {
continue
}
@@ -1799,7 +1855,7 @@ func (s *Service) refusePolicyAdmission(store Store, orgID string, record unifie
return unified.ActionAuditRecord{}, &PersistError{Op: "policy admission refusal", Err: persistErr}
}
s.publishTransition(orgID, failed)
s.publishCompleted(failed)
s.publishCompleted(orgID, failed)
return failed, reason
}
@@ -1949,14 +2005,14 @@ func RecordRefusedExecution(store Store, record unified.ActionAuditRecord, actor
return failed, nil
}
func (s *Service) publishCompleted(record unified.ActionAuditRecord) {
func (s *Service) publishCompleted(orgID string, record unified.ActionAuditRecord) {
if s == nil || s.OnActionCompleted == nil {
return
}
if record.State != unified.ActionStateCompleted && record.State != unified.ActionStateFailed {
return
}
s.OnActionCompleted(record)
s.OnActionCompleted(orgID, record)
}
// publishTransition notifies the persisted-state subscriber. Callers invoke
+153 -2
View File
@@ -234,6 +234,65 @@ func runConcurrentExecuteAdmitsExecutorExactlyOnce(t *testing.T, store unified.R
}
}
// An Execute that dispatches nothing is answered from the stored record, so
// it is a read of what others planned, approved and ran. Execute authority
// alone is refused with the lifecycle state, both while another call's
// dispatch is in flight and after the action settled; the call that ran the
// action still gets its own result.
func TestExecuteReplaysStoredRecordOnlyToReviewers(t *testing.T) {
executor := &blockingExecutor{entered: make(chan struct{}), release: make(chan struct{})}
service := serviceForStore(t, unified.NewMemoryStore(), testResource(time.Now().UTC(), unified.ApprovalNone), executor)
service.DecisionAuthorizer = DecisionAuthorizerFunc(func(_ context.Context, _ string, _ unified.ActionAuditRecord, decision unified.ActionDecision) error {
if decision.Actor.SubjectID != "reviewer" {
return ErrActionAuthorizationDenied
}
return nil
})
plan, err := service.Plan(context.Background(), "default", restartRequest(), testActionActor("requester", "default"))
if err != nil {
t.Fatal(err)
}
type outcome struct {
record unified.ActionAuditRecord
err error
}
execute := func(subject string) outcome {
record, err := service.Execute(context.Background(), "default", plan.ActionID, testActionActor(subject, "default"), "")
return outcome{record, err}
}
assertRefused := func(got outcome, want error) {
t.Helper()
if !errors.Is(got.err, want) || got.record.ID != "" {
t.Fatalf("execute-only replay = record %q err %v, want no record and %v", got.record.ID, got.err, want)
}
}
assertReplayed := func(got outcome, want unified.ActionState) {
t.Helper()
if got.err != nil || got.record.ID != plan.ActionID || got.record.State != want {
t.Fatalf("reviewer replay = record %q state %q err %v, want state %q", got.record.ID, got.record.State, got.err, want)
}
}
ran := make(chan outcome, 1)
go func() { ran <- execute("runner") }()
<-executor.entered
assertRefused(execute("bystander"), unified.ErrActionAlreadyExecuting)
assertReplayed(execute("reviewer"), unified.ActionStateExecuting)
close(executor.release)
if own := <-ran; own.err != nil || own.record.State != unified.ActionStateCompleted || own.record.Result == nil {
t.Fatalf("dispatching call = state %q err %v, want its own completed result", own.record.State, own.err)
}
assertRefused(execute("bystander"), unified.ErrActionExecutionFinal)
assertRefused(execute("runner"), unified.ErrActionExecutionFinal)
assertReplayed(execute("reviewer"), unified.ActionStateCompleted)
service.DecisionAuthorizer = nil
assertRefused(execute("reviewer"), unified.ErrActionExecutionFinal)
if executor.calls.Load() != 1 {
t.Fatalf("executor calls=%d, want 1", executor.calls.Load())
}
}
func TestConcurrentExecuteAdmitsExecutorExactlyOnceMemoryStore(t *testing.T) {
runConcurrentExecuteAdmitsExecutorExactlyOnce(t, unified.NewMemoryStore())
}
@@ -1047,7 +1106,7 @@ func newServiceEnv(t *testing.T, resource unified.Resource) *serviceEnv {
DecisionAuthorizer: DecisionAuthorizerFunc(func(context.Context, string, unified.ActionAuditRecord, unified.ActionDecision) error { return nil }),
ExecutionAuthorizer: ExecutionAuthorizerFunc(func(context.Context, string, unified.ActionAuditRecord, unified.ActionActor) error { return nil }),
LiveCheckAuthorizer: LiveCheckAuthorizerFunc(func(context.Context, string, unified.ActionActor) error { return nil }),
OnActionCompleted: func(record unified.ActionAuditRecord) {
OnActionCompleted: func(_ string, record unified.ActionAuditRecord) {
env.completed = append(env.completed, record)
},
}
@@ -1312,6 +1371,34 @@ func TestApprovalRechecksAgentFeasibilityBeforePersistingDecision(t *testing.T)
}
}
func TestApprovalRechecksAuthorityAfterTheAgentCheck(t *testing.T) {
now := time.Now().UTC()
env := newServiceEnv(t, testResource(now, unified.ApprovalAdmin))
plan, err := env.service.Plan(context.Background(), "default", restartRequest(), testActionActor("requester", "default"))
if err != nil {
t.Fatal(err)
}
// The reviewer's authority is withdrawn while the agent answers.
asked := env.executor.feasibilityCalls
env.service.DecisionAuthorizer = DecisionAuthorizerFunc(func(context.Context, string, unified.ActionAuditRecord, unified.ActionDecision) error {
if env.executor.feasibilityCalls > asked {
return ErrActionAuthorizationDenied
}
return nil
})
decision := testActionDecision(t, env.service, "default", plan.ActionID, unified.ActionApprovalRecord{Actor: "operator", Outcome: unified.OutcomeApproved})
if _, err := env.service.Decide(context.Background(), "default", plan.ActionID, decision); !errors.Is(err, ErrActionAuthorizationDenied) {
t.Fatalf("approval error=%v", err)
}
if env.executor.feasibilityCalls == asked {
t.Fatal("the agent was not asked, so authority was not withdrawn during the check")
}
current := mustActionRecord(t, env.service, plan.ActionID)
if current.State != unified.ActionStatePending || len(current.Approvals) != 0 {
t.Fatalf("withdrawn approval mutated record: %#v", current)
}
}
func TestRefreshReplacesExpiredPlanAndPreservesTrustedOrigin(t *testing.T) {
now := time.Now().UTC()
env := newServiceEnv(t, testResource(now, unified.ApprovalAdmin))
@@ -1358,6 +1445,28 @@ func mustActionRecord(t *testing.T, service *Service, actionID string) unified.A
return record
}
// The completion publisher feeds the agent event stream, which delivers an
// event only to the organization it is tagged with. The service must hand the
// publisher the organization whose store holds the action.
func TestCompletionPublisherReceivesOwningOrganization(t *testing.T) {
store := unified.NewMemoryStore()
executor := &stubExecutor{result: &unified.ExecutionResult{Success: true, Output: "restarted"}}
service := serviceForStore(t, store, testResource(time.Now().UTC(), unified.ApprovalNone), executor)
var orgs []string
service.OnActionCompleted = func(orgID string, _ unified.ActionAuditRecord) { orgs = append(orgs, orgID) }
plan, err := service.Plan(context.Background(), "tenant-b", restartRequest(), testActionActor("requester", "tenant-b"))
if err != nil {
t.Fatalf("Plan: %v", err)
}
if _, err := service.Execute(context.Background(), "tenant-b", plan.ActionID, testActionActor("operator", "tenant-b"), "restart"); err != nil {
t.Fatalf("Execute: %v", err)
}
if len(orgs) != 1 || orgs[0] != "tenant-b" {
t.Fatalf("completion publisher organizations = %q, want [tenant-b]", orgs)
}
}
func TestExecuteRunsApprovedActionToTerminalAudit(t *testing.T) {
now := time.Now().UTC()
env := newServiceEnv(t, testResource(now, unified.ApprovalAdmin))
@@ -1433,6 +1542,48 @@ func TestExecuteRefusesLostReadinessBeforeAdmission(t *testing.T) {
}
}
func TestExecuteRechecksAuthorityAfterTheAgentCheck(t *testing.T) {
now := time.Now().UTC()
env := newServiceEnv(t, testResource(now, unified.ApprovalAdmin))
plan, err := env.service.Plan(context.Background(), "default", restartRequest(), testActionActor("requester", "default"))
if err != nil {
t.Fatalf("Plan: %v", err)
}
if _, err := env.service.Decide(context.Background(), "default", plan.ActionID, testActionDecision(t, env.service, "default", plan.ActionID, unified.ActionApprovalRecord{
Actor: "operator", Method: unified.MethodAPI, Outcome: unified.OutcomeApproved,
})); err != nil {
t.Fatalf("Decide: %v", err)
}
// The caller's authority is withdrawn while the agent answers.
asked := env.executor.feasibilityCalls
env.service.ExecutionAuthorizer = ExecutionAuthorizerFunc(func(context.Context, string, unified.ActionAuditRecord, unified.ActionActor) error {
if env.executor.feasibilityCalls > asked {
return ErrActionAuthorizationDenied
}
return nil
})
if _, err := env.service.Execute(context.Background(), "default", plan.ActionID, testActionActor("operator", "default"), ""); !errors.Is(err, ErrActionAuthorizationDenied) {
t.Fatalf("error = %v, want ErrActionAuthorizationDenied", err)
}
if env.executor.feasibilityCalls == asked {
t.Fatal("the agent was not asked, so authority was not withdrawn during the check")
}
if env.executor.calls != 0 {
t.Fatalf("executor calls = %d, want no dispatch", env.executor.calls)
}
// The action is not refused: a caller who may still run it can.
if current := mustActionRecord(t, env.service, plan.ActionID); current.State != unified.ActionStateApproved {
t.Fatalf("state = %q, want approved", current.State)
}
if _, found, getErr := env.store.GetActionDispatchAttempt(plan.ActionID); getErr != nil || found {
t.Fatalf("dispatch attempt found=%v err=%v, want none", found, getErr)
}
if len(env.completed) != 0 {
t.Fatalf("completion publisher observed %#v", env.completed)
}
}
func TestExecuteRefusesUnapprovedActionWithoutDispatch(t *testing.T) {
now := time.Now().UTC()
env := newServiceEnv(t, testResource(now, unified.ApprovalAdmin))
@@ -2042,7 +2193,7 @@ func TestIssue1649ForceFailTerminalizesWedgedExecutingActionWithAudit(t *testing
service := serviceForStore(t, store, testResource(time.Now().UTC(), unified.ApprovalNone), executor)
var completed []unified.ActionAuditRecord
var transitions []unified.ActionAuditRecord
service.OnActionCompleted = func(record unified.ActionAuditRecord) { completed = append(completed, record) }
service.OnActionCompleted = func(_ string, record unified.ActionAuditRecord) { completed = append(completed, record) }
service.OnActionTransition = func(_ string, record unified.ActionAuditRecord) { transitions = append(transitions, record) }
plan, err := service.Plan(context.Background(), "default", restartRequest(), testActionActor("requester", "default"))
if err != nil {
+17
View File
@@ -18,6 +18,17 @@ import (
const DefaultPlanTTL = 5 * time.Minute
// A request's ID and reason are persisted verbatim with the request, the ID
// is repeated in the plan, and both are read back whenever the action is
// listed, decided or migrated. Bound them here, the single validation every
// planning transport shares, so caller-owned text cannot grow the action
// audit store without limit. The ID limit leaves room for in-process request
// IDs that embed resource identifiers (operational-trust IDs carry one twice).
const (
MaxRequestIDBytes = 1 << 10
MaxReasonBytes = 4 << 10
)
var ErrCapabilityNotFound = errors.New("resource capability is not advertised")
type ValidationError struct {
@@ -269,6 +280,9 @@ func validateRequest(req unified.ActionRequest) error {
if req.RequestID == "" {
return &ValidationError{Field: "requestId", Message: "request id is required"}
}
if len(req.RequestID) > MaxRequestIDBytes {
return &ValidationError{Field: "requestId", Message: fmt.Sprintf("request id must be at most %d bytes", MaxRequestIDBytes)}
}
if req.ResourceID == "" {
return &ValidationError{Field: "resourceId", Message: "resource id is required"}
}
@@ -278,6 +292,9 @@ func validateRequest(req unified.ActionRequest) error {
if req.Reason == "" {
return &ValidationError{Field: "reason", Message: "reason is required"}
}
if len(req.Reason) > MaxReasonBytes {
return &ValidationError{Field: "reason", Message: fmt.Sprintf("reason must be at most %d bytes", MaxReasonBytes)}
}
if err := unified.ValidateActionActor(req.Actor); err != nil {
return &ValidationError{Field: "actor", Message: err.Error()}
}
+36
View File
@@ -196,6 +196,42 @@ func TestPlannerRejectsUndeclaredParams(t *testing.T) {
}
}
func TestPlannerBoundsPersistedRequestText(t *testing.T) {
resource := unified.Resource{
ID: "vm:42",
Type: unified.ResourceTypeVM,
Capabilities: []unified.ResourceCapability{
{Name: "restart", Type: unified.CapabilityTypeCommon, MinimumApprovalLevel: unified.ApprovalAdmin},
},
}
request := func(requestID, reason string) unified.ActionRequest {
return unified.ActionRequest{
RequestID: requestID,
ResourceID: "vm:42",
CapabilityName: "restart",
Reason: reason,
Actor: unified.ActionActor{SubjectID: "agent:oncall-helper", Kind: unified.ActionActorService, CredentialID: "service:test", OrgID: "default"},
}
}
if _, err := (Planner{}).Plan(request(strings.Repeat("r", MaxRequestIDBytes), strings.Repeat("w", MaxReasonBytes)), resource); err != nil {
t.Fatalf("Plan() at the limits error = %v", err)
}
for field, req := range map[string]unified.ActionRequest{
"requestId": request(strings.Repeat("r", MaxRequestIDBytes+1), "Recover after confirmed outage"),
"reason": request("agent-run-123", strings.Repeat("w", MaxReasonBytes+1)),
} {
_, err := Planner{}.Plan(req, resource)
validationErr, ok := AsValidationError(err)
if !ok {
t.Fatalf("Plan() with oversized %s error = %v, want validation error", field, err)
}
if validationErr.Field != field {
t.Fatalf("validation field = %q, want %s", validationErr.Field, field)
}
}
}
func TestResourceVersionIgnoresObservationOnlyTimestamps(t *testing.T) {
base := unified.Resource{
ID: "vm:42",
+13
View File
@@ -5,6 +5,7 @@ import (
"sort"
"strings"
"time"
"unicode/utf8"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts/reducer"
@@ -214,6 +215,12 @@ func (m *Manager) UnacknowledgeAlert(alertID string) error {
return nil
}
// MaxOperationalSuppressionReasonRunes bounds the operator-written reason of a
// suppression. The reason is retained in the alert's lifecycle transitions, and
// every later alert event snapshots the whole alert, so an unbounded reason is
// multiplied by the transition bound in each subsequent event.
const MaxOperationalSuppressionReasonRunes = 240
// SuppressOperationalAlert moves one canonical operational record out of the
// default attention queue without changing the detector's underlying finding.
// Suppression is bounded by an optional expiry and remains inspectable.
@@ -231,6 +238,12 @@ func (m *Manager) SuppressOperationalAlert(
if reason == "" {
return fmt.Errorf("suppression reason is required")
}
if utf8.RuneCountInString(reason) > MaxOperationalSuppressionReasonRunes {
return fmt.Errorf(
"suppression reason must be at most %d characters",
MaxOperationalSuppressionReasonRunes,
)
}
now := m.policyNow().UTC()
if expiresAt != nil {
@@ -2,6 +2,7 @@ package alerts
import (
"slices"
"strings"
"testing"
"time"
@@ -237,6 +238,47 @@ func TestOperationalSuppressionSurvivesManagerRestart(t *testing.T) {
}
}
func TestSuppressOperationalAlertBoundsReason(t *testing.T) {
manager := newTestManager(t)
now := time.Now().UTC()
alert := &Alert{
ID: "container-health",
CanonicalState: "container-health",
CanonicalSpecID: "docker-container-health",
Type: "docker-container-health",
Level: AlertLevelWarning,
ResourceID: "app-container:web",
ResourceName: "web",
StartTime: now.Add(-time.Minute),
LastSeen: now,
}
manager.mu.Lock()
manager.setActiveAlertNoLock(alert.ID, alert)
manager.mu.Unlock()
oversized := strings.Repeat("x", MaxOperationalSuppressionReasonRunes+1)
if err := manager.SuppressOperationalAlert(alert.ID, "operator", oversized, nil); err == nil {
t.Fatal("SuppressOperationalAlert() accepted an oversized reason")
}
current := activeAlert(t, manager, alert.ID)
if current.OperationalRecord == nil ||
current.OperationalRecord.State == operationaltrust.OperationalSuppressed ||
current.OperationalRecord.Suppression != nil {
t.Fatalf("rejected suppression changed the record: %+v", current.OperationalRecord)
}
// The bound counts characters, and surrounding whitespace is not stored.
boundary := strings.Repeat("日", MaxOperationalSuppressionReasonRunes)
if err := manager.SuppressOperationalAlert(alert.ID, "operator", " "+boundary+" ", nil); err != nil {
t.Fatalf("SuppressOperationalAlert() error = %v", err)
}
current = activeAlert(t, manager, alert.ID)
if current.OperationalRecord == nil || current.OperationalRecord.Suppression == nil ||
current.OperationalRecord.Suppression.Reason != boundary {
t.Fatalf("boundary suppression = %+v", current.OperationalRecord)
}
}
func TestOperationalLifecycleRetriesDoNotDuplicateTransitionsAndRetainNewEvidence(t *testing.T) {
manager := newTestManager(t)
now := time.Now().UTC()
+56 -14
View File
@@ -70,8 +70,12 @@ func actionActorForRequest(cfg *config.Config, r *http.Request, orgID string) (u
if valid, proxyUser, _ := CheckProxyAuth(cfg, r); valid && strings.EqualFold(strings.TrimSpace(proxyUser), user) {
credentialID = actionCredentialID("proxy", user)
}
} else if authorization := strings.TrimSpace(r.Header.Get("Authorization")); authorization != "" {
credentialID = actionCredentialID("http-auth", authorization)
} else if strings.TrimSpace(r.Header.Get("Authorization")) != "" {
// A Basic header carries the password, and the credential ID is
// persisted and returned to every action reader. Bind the verified
// principal, as the proxy branch does: an unkeyed digest of the
// header would let a reader test password guesses offline.
credentialID = actionCredentialID("http-auth", user)
} else if adminBypassEnabled() {
credentialID = "development-bypass"
} else if strings.TrimSpace(auth.GetUser(r.Context())) != "" {
@@ -103,6 +107,28 @@ func approvalEvidenceForRequest(actor unified.ActionActor, record unified.Action
}
}
type liveActionCredentialContextKey struct{}
// withLiveActionCredential lets authorizeActor ask, every time the lifecycle
// consults it, whether the credential that admitted this request still holds
// the capability. Body reads, the admission lock and the agent's answer to a
// check can outlive revocation, a scope edit or sign-out, and the request's
// own token record is a detached snapshot that shows none of them. A token is
// re-read in place of a session, as at admission. Proxy and basic credentials
// have nothing to re-read and stay with the route.
func withLiveActionCredential(cfg *config.Config, r *http.Request) context.Context {
session := sessionReadRevalidator(r)
live := func(capability string) bool {
token := tokenStreamSnapshotRevalidator(cfg, r, actionCapabilityScopes(capability)...)
if token == nil {
return session == nil || session()
}
_, ok := token()
return ok
}
return context.WithValue(r.Context(), liveActionCredentialContextKey{}, live)
}
type actionAuthority struct {
authorizer auth.Authorizer
orgChecker *DefaultAuthorizationChecker
@@ -110,6 +136,9 @@ type actionAuthority struct {
func (a actionAuthority) authorizeActor(ctx context.Context, orgID string, actor unified.ActionActor, capability string) error {
actor = unified.NormalizeActionActor(actor)
if live, ok := ctx.Value(liveActionCredentialContextKey{}).(func(string) bool); ok && !live(capability) {
return actionlifecycle.ErrActionAuthorizationDenied
}
var token *config.APITokenRecord
if actor.Kind == unified.ActionActorAPIToken {
current, ok := auth.GetAPIToken(ctx).(*config.APITokenRecord)
@@ -133,22 +162,31 @@ func (a actionAuthority) authorizeActor(ctx context.Context, orgID string, actor
return authorizeActionCapability(ctx, a.authorizer, capability)
}
func tokenHasActionCapabilityScope(token *config.APITokenRecord, capability string) bool {
if token == nil {
return false
}
var scopes []string
func actionCapabilityScopes(capability string) []string {
switch capability {
case auth.ActionPlan:
scopes = []string{config.ScopeActionsPlan, config.ScopeAIExecute}
return []string{config.ScopeActionsPlan, config.ScopeAIExecute}
case auth.ActionApprove:
scopes = []string{config.ScopeActionsApprove, config.ScopeAIExecute, config.ScopeRelayMobileAccess}
return []string{config.ScopeActionsApprove, config.ScopeAIExecute, config.ScopeRelayMobileAccess}
case auth.ActionExecute:
scopes = []string{config.ScopeActionsExecute, config.ScopeAIExecute, config.ScopeRelayMobileAccess}
return []string{config.ScopeActionsExecute, config.ScopeAIExecute, config.ScopeRelayMobileAccess}
default:
return nil
}
}
// tokenActionsWithheld reports whether a token was minted by a caller who
// could not review or run actions (apiTokenMetadataActionsWithheld). Such a
// token's scopes grant no action capability.
func tokenActionsWithheld(token *config.APITokenRecord) bool {
return token != nil && token.Metadata[apiTokenMetadataActionsWithheld] == "true"
}
func tokenHasActionCapabilityScope(token *config.APITokenRecord, capability string) bool {
if token == nil || tokenActionsWithheld(token) {
return false
}
for _, scope := range scopes {
for _, scope := range actionCapabilityScopes(capability) {
if token.HasScope(scope) {
return true
}
@@ -214,6 +252,10 @@ func authorizeActionCapability(ctx context.Context, authorizer auth.Authorizer,
// action lifecycle.
func requireActionCapability(cfg *config.Config, authorizer auth.Authorizer, capability string, handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if tokenActionsWithheld(getAPITokenRecordFromRequest(r)) {
writeJSONError(w, http.StatusForbidden, "action_capability_denied", "Administrator privileges or an explicit action grant are required")
return
}
if _, isDefaultAuthorizer := authorizer.(*auth.DefaultAuthorizer); isDefaultAuthorizer && getAPITokenRecordFromRequest(r) == nil {
if cfg != nil && strings.TrimSpace(cfg.ProxyAuthSecret) != "" {
if valid, _, isAdmin := CheckProxyAuth(cfg, r); valid && !isAdmin {
@@ -341,8 +383,8 @@ func assistantSessionContext(ctx context.Context) context.Context {
// approval) and must still pass the authorizer, so an RBAC role without the
// plan grant cannot plan through a token either.
func assistantRequestHasActionPlanCapability(cfg *config.Config, authorizer auth.Authorizer, r *http.Request) bool {
if getAPITokenRecordFromRequest(r) != nil {
return authorizeActionCapability(r.Context(), authorizer, auth.ActionPlan) == nil
if record := getAPITokenRecordFromRequest(r); record != nil {
return !tokenActionsWithheld(record) && authorizeActionCapability(r.Context(), authorizer, auth.ActionPlan) == nil
}
return requestHasActionCapability(cfg, authorizer, r, auth.ActionPlan)
}
@@ -361,7 +403,7 @@ func assistantActionPlanAuthorityFromContext(ctx context.Context) bool {
func requireAIApprovalReview(cfg *config.Config, authorizer auth.Authorizer, handler http.HandlerFunc) http.HandlerFunc {
sessionReview := requireActionCapability(cfg, authorizer, auth.ActionApprove, handler)
return func(w http.ResponseWriter, r *http.Request) {
if getAPITokenRecordFromRequest(r) != nil {
if record := getAPITokenRecordFromRequest(r); record != nil && !tokenActionsWithheld(record) {
handler(w, r)
return
}
+89
View File
@@ -96,6 +96,30 @@ func TestDefaultActionAuthorityAllowsConfiguredAdminBrowserSession(t *testing.T)
}
}
func TestActionActorCredentialIDDoesNotDependOnBasicPassword(t *testing.T) {
actorFor := func(password string) unified.ActionActor {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/actions/plan", nil)
req.SetBasicAuth("admin", password)
req = req.WithContext(auth.WithUser(req.Context(), "admin"))
actor, err := actionActorForRequest(&config.Config{AuthUser: "admin"}, req, "default")
if err != nil {
t.Fatalf("resolve Basic auth action actor: %v", err)
}
return actor
}
first, second := actorFor("first-password"), actorFor("second-password")
if first.Kind != unified.ActionActorUser || first.SubjectID != "admin" || !strings.HasPrefix(first.CredentialID, "http-auth:") {
t.Fatalf("unexpected Basic auth action actor: %+v", first)
}
// The credential ID is persisted and returned to action readers, so it
// must not let them recognise a guessed password.
if first.CredentialID != second.CredentialID {
t.Fatalf("credential ID varies with the Basic auth password: %q vs %q", first.CredentialID, second.CredentialID)
}
}
func TestExplicitActionAuthorizerCanGrantNonAdminBrowserSession(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/api/actions/act-test/execute", nil)
req = req.WithContext(auth.WithUser(req.Context(), "operator"))
@@ -283,3 +307,68 @@ func TestHandleExecuteActionRejectsExecutorWithoutCurrentCapability(t *testing.T
t.Fatalf("error=%v", err)
}
}
func TestActionAuthorityRereadsTheAdmittedToken(t *testing.T) {
const raw = "synthetic-action-executor.12345678"
for _, change := range []string{"revoked", "scope"} {
t.Run(change, func(t *testing.T) {
record := newTokenRecord(t, raw, []string{config.ScopeActionsExecute}, nil)
setAPITokenOwnerUserID(&record, "alice")
cfg := newTestConfigWithTokens(t, record)
req := httptest.NewRequest(http.MethodPost, "/api/actions/act-test/execute", nil)
req.Header.Set("X-API-Token", raw)
var ctx context.Context
var actor unified.ActionActor
AuthContextMiddleware(cfg, nil, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
var err error
if actor, err = actionActorForRequest(cfg, r, "default"); err != nil {
t.Fatal(err)
}
ctx = context.WithoutCancel(withLiveActionCredential(cfg, r))
})).ServeHTTP(httptest.NewRecorder(), req)
if ctx == nil {
t.Fatal("token admission failed")
}
authority := testActionAuthority()
if err := authority.AuthorizeExecution(ctx, "default", unified.ActionAuditRecord{}, actor); err != nil {
t.Fatal(err)
}
config.Mu.Lock()
if change == "revoked" {
cfg.RemoveAPIToken(cfg.APITokens[0].ID)
} else {
cfg.APITokens[0].Scopes = []string{config.ScopeActionsApprove}
}
config.Mu.Unlock()
// The request still carries the record it was admitted with.
if err := authority.AuthorizeExecution(ctx, "default", unified.ActionAuditRecord{}, actor); !errors.Is(err, actionlifecycle.ErrActionAuthorizationDenied) {
t.Fatalf("execute after %s=%v", change, err)
}
})
}
}
func TestActionAuthorityRereadsTheAdmittedSession(t *testing.T) {
InitSessionStore(t.TempDir())
const raw = "synthetic-action-session"
GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", "alice")
req := httptest.NewRequest(http.MethodPost, "http://127.0.0.1/api/actions/act-test/execute", nil)
req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: raw})
if !CheckAuth(&config.Config{}, httptest.NewRecorder(), req) {
t.Fatal("session admission failed")
}
req = req.WithContext(auth.WithUser(req.Context(), "alice"))
actor, err := actionActorForRequest(&config.Config{}, req, "default")
if err != nil {
t.Fatal(err)
}
ctx := context.WithoutCancel(withLiveActionCredential(&config.Config{}, req))
authority := testActionAuthority()
if err := authority.AuthorizeExecution(ctx, "default", unified.ActionAuditRecord{}, actor); err != nil {
t.Fatal(err)
}
GetSessionStore().InvalidateSession(raw)
if err := authority.AuthorizeExecution(ctx, "default", unified.ActionAuditRecord{}, actor); !errors.Is(err, actionlifecycle.ErrActionAuthorizationDenied) {
t.Fatalf("execute after sign-out=%v", err)
}
}
+3 -3
View File
@@ -19,7 +19,7 @@ import (
"github.com/rs/zerolog/log"
)
const maxActionPlanRequestBytes = 1 << 20
const maxActionPlanRequestBytes = 64 << 10
const maxActionDecisionRequestBytes = 64 << 10
const maxActionExecutionRequestBytes = 64 << 10
const maxActionRefreshRequestBytes = 64 << 10
@@ -523,7 +523,7 @@ func (h *ResourceHandlers) HandleDecideAction(w http.ResponseWriter, r *http.Req
Reason: decision.Reason,
Evidence: approvalEvidenceForRequest(actor, record, decision.Outcome, time.Now().UTC()),
}
updated, err := lifecycle.Decide(r.Context(), orgID, actionID, canonicalDecision)
updated, err := lifecycle.Decide(withLiveActionCredential(h.cfg, r), orgID, actionID, canonicalDecision)
if err != nil {
writeActionLifecycleReadError(w, err, func() {
if writeActionReadinessError(w, err) {
@@ -739,7 +739,7 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Re
// finish, and a cancelled request context would abandon the committed
// dispatch mid-flight and strand the action in executing. The transport
// wait stays bounded by the per-operation timeout and server shutdown.
completed, err := h.ActionLifecycle().Execute(context.WithoutCancel(r.Context()), orgID, actionID, actor, execution.Reason)
completed, err := h.ActionLifecycle().Execute(context.WithoutCancel(withLiveActionCredential(h.cfg, r)), orgID, actionID, actor, execution.Reason)
if err != nil {
writeActionLifecycleReadError(w, err, func() {
writeActionExecuteError(w, err)
+154 -5
View File
@@ -674,7 +674,7 @@ func TestHandleExecuteActionRunsApprovedPlanThroughExecutor(t *testing.T) {
executor := &stubActionExecutor{result: &unified.ExecutionResult{Success: true, Output: "restart dispatched"}}
h.SetActionExecutor(executor)
published := make(chan unified.ActionAuditRecord, 1)
h.SetActionCompletedPublisher(func(record unified.ActionAuditRecord) {
h.SetActionCompletedPublisher(func(_ string, record unified.ActionAuditRecord) {
published <- record
})
@@ -770,6 +770,155 @@ func TestHandleExecuteActionRunsApprovedPlanThroughExecutor(t *testing.T) {
}
}
type heldActionExecutor struct {
stubActionExecutor
entered chan struct{}
release chan struct{}
}
func (e *heldActionExecutor) ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {
close(e.entered)
<-e.release
return e.stubActionExecutor.ExecuteAction(ctx, record)
}
// An execute that dispatches nothing (the action is already final, or another
// caller holds its dispatch) is answered from the stored record, so it is a
// read. An actions:execute token, which GET /api/actions/{id} refuses, gets
// the lifecycle refusal instead; a token that may also review the action
// keeps the replay, and the token whose request ran the action still gets the
// result in that request's own answer.
func TestHandleExecuteActionReplaysRecordOnlyToActionReviewers(t *testing.T) {
now := time.Date(2026, 5, 4, 14, 0, 0, 0, time.UTC)
const (
runnerRaw = "synthetic-execute-runner.12345678"
bystanderRaw = "synthetic-execute-bystander.12345678"
reviewerRaw = "synthetic-execute-reviewer.12345678"
)
runnerRec := newTokenRecord(t, runnerRaw, []string{config.ScopeActionsExecute}, nil)
runnerRec.ID = "execute-runner"
setAPITokenOwnerUserID(&runnerRec, "operator@example.com")
bystanderRec := newTokenRecord(t, bystanderRaw, []string{config.ScopeActionsExecute}, nil)
bystanderRec.ID = "execute-bystander"
setAPITokenOwnerUserID(&bystanderRec, "integration@example.com")
reviewerRec := newTokenRecord(t, reviewerRaw, []string{config.ScopeActionsExecute, config.ScopeActionsApprove}, nil)
reviewerRec.ID = "execute-reviewer"
setAPITokenOwnerUserID(&reviewerRec, "operator@example.com")
cfg := &config.Config{
DataPath: t.TempDir(),
APITokens: []config.APITokenRecord{runnerRec, bystanderRec, reviewerRec},
}
h := NewResourceHandlers(cfg)
authority := testActionAuthority()
h.SetActionAuthorizers(authority, authority, authority)
h.SetStateProvider(resourceUnifiedSeedProvider{
snapshot: models.StateSnapshot{LastUpdate: now},
resources: []unified.Resource{{
ID: "vm:42", Type: unified.ResourceTypeVM, Name: "web-42", Status: unified.StatusWarning,
LastSeen: now, UpdatedAt: now, Sources: []unified.DataSource{unified.SourceProxmox},
Capabilities: []unified.ResourceCapability{{
Name: "restart", Type: unified.CapabilityTypeCommon, Description: "Restart the VM",
MinimumApprovalLevel: unified.ApprovalAdmin, InternalHandler: "proxmox.vm.restart",
}},
}},
})
executor := &heldActionExecutor{
stubActionExecutor: stubActionExecutor{result: &unified.ExecutionResult{Success: true, Output: "restart dispatched"}},
entered: make(chan struct{}),
release: make(chan struct{}),
}
h.SetActionExecutor(executor)
planRec := httptest.NewRecorder()
planReq := httptest.NewRequest(http.MethodPost, "/api/actions/plan", bytes.NewBufferString(`{
"requestId":"agent-run-execute-replay",
"resourceId":"vm:42",
"capabilityName":"restart",
"reason":"Recover after confirmed outage"
}`))
h.HandlePlanAction(planRec, actionHandlerTestRequest(planReq, ""))
if planRec.Code != http.StatusOK {
t.Fatalf("plan status = %d, body=%s", planRec.Code, planRec.Body.String())
}
var plan unified.ActionPlan
if err := json.Unmarshal(planRec.Body.Bytes(), &plan); err != nil {
t.Fatalf("decode plan response: %v", err)
}
decisionRec := httptest.NewRecorder()
decisionReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+plan.ActionID+"/decision", bytes.NewBufferString(`{
"outcome":"approved",
"reason":"approver-only rationale"
}`))
decisionReq.SetPathValue("id", plan.ActionID)
h.HandleDecideAction(decisionRec, actionHandlerTestRequest(decisionReq, "operator@example.com"))
if decisionRec.Code != http.StatusOK {
t.Fatalf("decision status = %d, body=%s", decisionRec.Code, decisionRec.Body.String())
}
runner := &runnerRec
bystander := &bystanderRec
reviewer := &reviewerRec
execute := func(token *config.APITokenRecord, raw, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/api/actions/"+plan.ActionID+"/execute", bytes.NewBufferString(body))
req.Header.Set("X-API-Token", raw)
req.SetPathValue("id", plan.ActionID)
rec := httptest.NewRecorder()
h.HandleExecuteAction(rec, req.WithContext(actionAuthorityContext(token)))
return rec
}
assertRefused := func(rec *httptest.ResponseRecorder, code string) {
t.Helper()
if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), code) {
t.Fatalf("execute-only status = %d, want 409 %s, body=%s", rec.Code, code, rec.Body.String())
}
for _, recorded := range []string{"restart dispatched", "approver-only rationale", "Recover after confirmed outage", "operator@example.com"} {
if strings.Contains(rec.Body.String(), recorded) {
t.Fatalf("execute-only answer disclosed %q: %s", recorded, rec.Body.String())
}
}
}
assertReplayed := func(rec *httptest.ResponseRecorder, state unified.ActionState) {
t.Helper()
var answer actionExecutionResponse
if rec.Code != http.StatusOK {
t.Fatalf("reviewer status = %d, body=%s", rec.Code, rec.Body.String())
}
if err := json.Unmarshal(rec.Body.Bytes(), &answer); err != nil {
t.Fatalf("decode reviewer answer: %v", err)
}
if answer.State != state || len(answer.Audit.Approvals) != 1 {
t.Fatalf("reviewer answer = %#v, want state %q with the approval", answer, state)
}
}
ran := make(chan *httptest.ResponseRecorder, 1)
go func() { ran <- execute(runner, runnerRaw, `{}`) }()
select {
case <-executor.entered:
case rec := <-ran:
t.Fatalf("runner finished before entering executor: status=%d body=%s", rec.Code, rec.Body.String())
}
assertRefused(execute(bystander, bystanderRaw, `{}`), "action_already_executing")
assertReplayed(execute(reviewer, reviewerRaw, `{}`), unified.ActionStateExecuting)
close(executor.release)
if own := <-ran; own.Code != http.StatusOK || !strings.Contains(own.Body.String(), "restart dispatched") || !strings.Contains(own.Body.String(), "approver-only rationale") {
t.Fatalf("executing caller status = %d, body=%s", own.Code, own.Body.String())
}
for _, body := range []string{`{}`, `{"planHash":"` + plan.PlanHash + `"}`} {
assertRefused(execute(bystander, bystanderRaw, body), "action_execution_final")
}
settled := execute(reviewer, reviewerRaw, `{}`)
assertReplayed(settled, unified.ActionStateCompleted)
if !strings.Contains(settled.Body.String(), "restart dispatched") {
t.Fatalf("reviewer replay lost the result: %s", settled.Body.String())
}
if executor.calls != 1 {
t.Fatalf("executor calls = %d, want 1", executor.calls)
}
}
func TestHandleExecuteActionReturnsStableLostReadinessRefusal(t *testing.T) {
now := time.Date(2026, 7, 20, 20, 0, 0, 0, time.UTC)
h := newActionTestResourceHandlers(t, &config.Config{DataPath: t.TempDir()})
@@ -805,7 +954,7 @@ func TestHandleExecuteActionReturnsStableLostReadinessRefusal(t *testing.T) {
}
h.SetActionExecutor(executor)
published := make(chan unified.ActionAuditRecord, 1)
h.SetActionCompletedPublisher(func(record unified.ActionAuditRecord) { published <- record })
h.SetActionCompletedPublisher(func(_ string, record unified.ActionAuditRecord) { published <- record })
planRec := httptest.NewRecorder()
planReq := httptest.NewRequest(http.MethodPost, "/api/actions/plan", bytes.NewBufferString(`{
@@ -915,7 +1064,7 @@ func TestHandleExecuteActionRejectsStalePlanBeforeExecutor(t *testing.T) {
executor := &stubActionExecutor{result: &unified.ExecutionResult{Success: true, Output: "should not run"}}
h.SetActionExecutor(executor)
published := make(chan unified.ActionAuditRecord, 1)
h.SetActionCompletedPublisher(func(record unified.ActionAuditRecord) {
h.SetActionCompletedPublisher(func(_ string, record unified.ActionAuditRecord) {
published <- record
})
@@ -1087,7 +1236,7 @@ func TestHandleExecuteActionRejectsDryRunOnlyPlan(t *testing.T) {
executor := &stubActionExecutor{result: &unified.ExecutionResult{Success: true, Output: "should not run"}}
h.SetActionExecutor(executor)
published := make(chan unified.ActionAuditRecord, 1)
h.SetActionCompletedPublisher(func(record unified.ActionAuditRecord) {
h.SetActionCompletedPublisher(func(_ string, record unified.ActionAuditRecord) {
published <- record
})
@@ -1163,7 +1312,7 @@ func TestHandleExecuteActionMaterializesExplicitExpiredState(t *testing.T) {
executor := &stubActionExecutor{result: &unified.ExecutionResult{Success: true, Output: "should not run"}}
h.SetActionExecutor(executor)
published := make(chan unified.ActionAuditRecord, 1)
h.SetActionCompletedPublisher(func(record unified.ActionAuditRecord) {
h.SetActionCompletedPublisher(func(_ string, record unified.ActionAuditRecord) {
published <- record
})
+2 -2
View File
@@ -119,7 +119,7 @@ func TestAgentActionDisclosureAcrossProducersAndScopes(t *testing.T) {
broadcaster := NewAgentEventBroadcaster()
events, unsubscribe := broadcaster.Subscribe()
defer unsubscribe()
broadcaster.PublishActionCompletedRecord(record)
broadcaster.PublishActionCompletedRecord("default", record)
for _, event := range []AgentEvent{
{Kind: AgentEventActionCompleted, Payload: payload},
{Kind: AgentEventActionCompleted, Payload: &payload},
@@ -279,7 +279,7 @@ func TestAgentActionDisclosureConcurrentSSESubscribers(t *testing.T) {
t.Fatal("both streams must subscribe before publish")
}
record := agentDisclosureRecord(t, false)
b.PublishActionCompletedRecord(record)
b.PublishActionCompletedRecord("default", record)
var wg sync.WaitGroup
for _, client := range clients {
wg.Add(1)
+10 -4
View File
@@ -377,10 +377,13 @@ func (b *AgentEventBroadcaster) PublishFindingCreated(orgID string, payload Agen
// store's post-create hook routes through. Wraps the payload in the
// canonical envelope and forwards to Publish — the broadcaster
// stamps the timestamp and event id.
func (b *AgentEventBroadcaster) PublishApprovalPending(payload AgentEventApprovalPendingPayload) {
// The event reaches only orgID's subscribers: an approval belongs to the
// organization that requested it.
func (b *AgentEventBroadcaster) PublishApprovalPending(orgID string, payload AgentEventApprovalPendingPayload) {
b.Publish(AgentEvent{
Kind: AgentEventApprovalPending,
Payload: payload,
orgID: normalizeAgentEventOrgID(orgID),
})
}
@@ -388,10 +391,13 @@ func (b *AgentEventBroadcaster) PublishApprovalPending(payload AgentEventApprova
// post-completion hook routes through. Wraps the payload in the
// canonical envelope and forwards to Publish — the broadcaster
// stamps the timestamp and event id.
func (b *AgentEventBroadcaster) PublishActionCompleted(payload AgentEventActionCompletedPayload) {
// The event reaches only orgID's subscribers: an action belongs to the
// organization whose action store holds it.
func (b *AgentEventBroadcaster) PublishActionCompleted(orgID string, payload AgentEventActionCompletedPayload) {
b.Publish(AgentEvent{
Kind: AgentEventActionCompleted,
Payload: payload,
orgID: normalizeAgentEventOrgID(orgID),
})
}
@@ -400,7 +406,7 @@ func (b *AgentEventBroadcaster) PublishActionCompleted(payload AgentEventActionC
// API-owned execution endpoint route through this helper so agents hear the
// same completion event regardless of which execution surface dispatched the
// action.
func (b *AgentEventBroadcaster) PublishActionCompletedRecord(record unifiedresources.ActionAuditRecord) {
func (b *AgentEventBroadcaster) PublishActionCompletedRecord(orgID string, record unifiedresources.ActionAuditRecord) {
if b == nil {
return
}
@@ -426,7 +432,7 @@ func (b *AgentEventBroadcaster) PublishActionCompletedRecord(record unifiedresou
if v := projectAgentResourceVerification(unifiedresources.CanonicalActionVerification(record)); v != nil {
payload.Verification = v
}
b.PublishActionCompleted(payload)
b.PublishActionCompleted(orgID, payload)
}
// AgentEventBroadcasterContextKey is the context key used to plumb
+12 -2
View File
@@ -56,19 +56,25 @@ func tokenStreamSnapshotRevalidator(cfg *config.Config, req *http.Request, scope
orgID := GetOrgID(req.Context())
source, tenantInventory := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource)
tenantInventory = tenantInventory && source.orgID != "" && source.orgID != "default"
checker := NewAuthorizationChecker(nil)
// Recheck the policy that admitted the request, so the stream of a token
// that acts for its owner also ends when the owner loses membership.
// A request TenantMiddleware did not admit rechecks the binding only.
var checker AuthorizationChecker = NewAuthorizationChecker(nil)
if policy, ok := req.Context().Value(orgAccessCheckerContextKey{}).(AuthorizationChecker); ok && policy != nil {
checker = policy
}
return func() (*config.APITokenRecord, bool) {
if !provided || raw == "" {
return nil, false
}
config.Mu.RLock()
defer config.Mu.RUnlock()
live := cfg
if tenantInventory {
live = tenantTokenConfigForRequest(req)
if live == nil {
config.Mu.RUnlock()
return nil, false
}
}
@@ -77,8 +83,12 @@ func tokenStreamSnapshotRevalidator(cfg *config.Config, req *http.Request, scope
// when its current owner disappears or revokes the credential.
current, ok := validateAPITokenLocked(live, raw)
if !ok || (tenantInventory && tenantTokenConfigForRequest(req) != live) {
config.Mu.RUnlock()
return nil, false
}
// Release the global config lock before checking organization
// membership, which may read organization metadata from disk.
config.Mu.RUnlock()
// Keep the route's existing scope alternatives (notably mobile chat)
// rather than requiring a new grant or pinning one interchangeable scope.
hasScope := false
+5 -5
View File
@@ -228,9 +228,9 @@ func TestAgentEventTokenRefreshKeepsBoundedContext(t *testing.T) {
}
config.Mu.Unlock()
if flushed%2 == 0 {
broadcaster.PublishApprovalPending(AgentEventApprovalPendingPayload{ApprovalID: "refresh-approval", Command: agentPrivateDetail})
broadcaster.PublishApprovalPending(orgID, AgentEventApprovalPendingPayload{ApprovalID: "refresh-approval", Command: agentPrivateDetail})
} else {
broadcaster.PublishActionCompletedRecord(record)
broadcaster.PublishActionCompletedRecord(orgID, record)
}
flushed++
}
@@ -277,7 +277,7 @@ func TestAgentEventTokenLifecycleRejectsWithdrawnAuthority(t *testing.T) {
}
config.Mu.Unlock()
router.agentEventBroadcaster.PublishActionCompletedRecord(agentDisclosureRecord(t, false))
router.agentEventBroadcaster.PublishActionCompletedRecord("default", agentDisclosureRecord(t, false))
primary.wantClosed(t)
event := control.next(t)
if event.Kind != AgentEventActionCompleted {
@@ -384,7 +384,7 @@ func TestAgentEventTokenLifecyclePreservesSessionDisclosure(t *testing.T) {
GetSessionStore().CreateSession(session, time.Hour, "fixture", "127.0.0.1", "operator")
t.Cleanup(func() { GetSessionStore().DeleteSession(session) })
stream := openAgentLifecycleStream(t, server, session, "session")
router.agentEventBroadcaster.PublishActionCompletedRecord(agentDisclosureRecord(t, false))
router.agentEventBroadcaster.PublishActionCompletedRecord("default", agentDisclosureRecord(t, false))
body, _ := json.Marshal(stream.next(t))
assertAgentDisclosureWire(t, body, false)
}
@@ -432,7 +432,7 @@ func TestAgentEventTokenLifecycleMCPConsumer(t *testing.T) {
config.Mu.Lock()
cfg.RemoveAPIToken(cfg.APITokens[0].ID)
config.Mu.Unlock()
router.agentEventBroadcaster.PublishActionCompletedRecord(agentDisclosureRecord(t, false))
router.agentEventBroadcaster.PublishActionCompletedRecord("default", agentDisclosureRecord(t, false))
select {
case err := <-done:
if err != nil {
+6 -6
View File
@@ -340,7 +340,7 @@ func TestAgentEventBroadcaster_PublishApprovalPendingDelivers(t *testing.T) {
expires := time.Now().Add(5 * time.Minute).UTC()
requested := time.Now().UTC()
b.PublishApprovalPending(AgentEventApprovalPendingPayload{
b.PublishApprovalPending("default", AgentEventApprovalPendingPayload{
ApprovalID: "appr-1",
ResourceID: "container:web-1",
TargetType: "container",
@@ -478,7 +478,7 @@ func TestAgentEventBroadcaster_PublishActionCompletedDelivers(t *testing.T) {
defer unsub()
completed := time.Now().UTC()
b.PublishActionCompleted(AgentEventActionCompletedPayload{
b.PublishActionCompleted("default", AgentEventActionCompletedPayload{
ActionID: "action-1",
ResourceID: "container:web-1",
CapabilityName: "pulse_docker",
@@ -535,7 +535,7 @@ func TestAgentEventBroadcaster_PublishActionCompletedPreservesRefusalToken(t *te
events, unsub := b.Subscribe()
defer unsub()
b.PublishActionCompleted(AgentEventActionCompletedPayload{
b.PublishActionCompleted("default", AgentEventActionCompletedPayload{
ActionID: "action-refused",
ResourceID: "vm:db-1",
State: "failed",
@@ -580,7 +580,7 @@ func TestAgentEventBroadcaster_PublishActionCompletedRoundTripsVerification(t *t
defer unsub()
ranAt := time.Now().UTC()
b.PublishActionCompleted(AgentEventActionCompletedPayload{
b.PublishActionCompleted("default", AgentEventActionCompletedPayload{
ActionID: "action-verify-1",
ResourceID: "container:web-1",
State: "completed",
@@ -616,7 +616,7 @@ func TestAgentEventBroadcaster_PublishActionCompletedRoundTripsVerification(t *t
recordBroadcaster := NewAgentEventBroadcaster()
recordEvents, recordUnsub := recordBroadcaster.Subscribe()
defer recordUnsub()
recordBroadcaster.PublishActionCompletedRecord(unifiedresources.ActionAuditRecord{
recordBroadcaster.PublishActionCompletedRecord("default", unifiedresources.ActionAuditRecord{
ID: "action-verify-record",
UpdatedAt: ranAt,
State: unifiedresources.ActionStateCompleted,
@@ -716,7 +716,7 @@ func TestAgentEventBroadcaster_PublishActionCompletedAbsentVerificationOmitsFiel
events, unsub := b.Subscribe()
defer unsub()
b.PublishActionCompleted(AgentEventActionCompletedPayload{
b.PublishActionCompleted("default", AgentEventActionCompletedPayload{
ActionID: "action-refused-1",
ResourceID: "vm:db-1",
State: "failed",
@@ -1475,6 +1475,64 @@ func TestAgentOperationsLoopExternalAgentTokenReadyUsesPulseMCPSurfaceScopes(t *
}
}
// The readiness check clones every token record until one covers the Pulse
// MCP surface. A bound collector may repeat its own authority reduction, and
// each call assigns keys of the live record's Metadata map under config.Mu, so
// the provider must read a detached copy taken under that lock: a map shared
// with the live inventory ends the process with "concurrent map iteration and
// map write". Run with -race: a shared map is reported as a data race.
func TestExternalAgentReadinessReadsTheTokenInventoryUnderTheConfigLock(t *testing.T) {
record, err := config.NewAPITokenRecord("readiness-collector-test.12345678", "collector", []string{
config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeAgentExec,
})
if err != nil {
t.Fatal(err)
}
record.OrgID = "default"
record.Metadata = map[string]string{"bound_agent_id": "agent-a", "bound_hostname": "node.example"}
cfg := &config.Config{DataPath: t.TempDir(), APITokens: []config.APITokenRecord{*record}}
router := newTestRouter(t, cfg, nil, nil, nil, nil, "test")
stop := make(chan struct{})
writerDone := make(chan struct{})
writerStatus := make(chan int, 1)
go func() {
defer close(writerDone)
for {
select {
case <-stop:
return
default:
}
req := httptest.NewRequest(http.MethodPost, "/api/agents/collector/reduce-authority",
strings.NewReader(`{"agentId":"agent-a","hostname":"node.example"}`))
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "default"))
attachAPITokenRecord(req, record)
rec := httptest.NewRecorder()
router.handleReduceCollectorAuthority(rec, req)
if rec.Code != http.StatusNoContent {
writerStatus <- rec.Code
return
}
}
}()
manifest := agentcapabilities.CanonicalManifest()
for i := 0; i < 2000; i++ {
if router.agentContextHandler.agentOperationsLoopExternalAgentReady(context.Background(), manifest, time.Now().UTC()) {
t.Fatal("a collector credential must not satisfy external-agent readiness")
}
}
close(stop)
<-writerDone
select {
case status := <-writerStatus:
t.Fatalf("repeated collector authority reduction answered %d, want 204", status)
default:
}
}
func TestHandleAgentOperationsLoopStatus_AggregatesContentSafeLoopCounts(t *testing.T) {
h, findings, approvals := fleetFixtureHandlers(t, []unified.Resource{
{ID: "vm:101", Type: "vm", Name: "db-01"},
+2 -2
View File
@@ -2452,7 +2452,7 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
// Parse request
var req ChatRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
@@ -2917,7 +2917,7 @@ func (h *AIHandler) HandleRenameSession(w http.ResponseWriter, r *http.Request,
}
var req RenameSessionRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
+20 -20
View File
@@ -3507,7 +3507,7 @@ func (h *AISettingsHandler) HandleTestProvider(w http.ResponseWriter, r *http.Re
var body aiProviderTestRequest
if r.ContentLength > 0 {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&body); err != nil {
http.Error(w, `{"error":"Invalid JSON body"}`, http.StatusBadRequest)
return
}
@@ -4057,7 +4057,7 @@ func (h *AISettingsHandler) HandleAnalyzeKubernetesCluster(w http.ResponseWriter
r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
var req AIKubernetesAnalyzeRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -4128,7 +4128,7 @@ func (h *AISettingsHandler) HandleExecuteStream(w http.ResponseWriter, r *http.R
// Parse request
r.Body = http.MaxBytesReader(w, r.Body, 64*1024) // 64KB max
var req AIExecuteRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
log.Warn().Err(err).Msg("Failed to decode AI execute stream request")
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
@@ -4382,7 +4382,7 @@ func (h *AISettingsHandler) HandleSaveGuestNote(w http.ResponseWriter, r *http.R
Content string `json:"content"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -4431,7 +4431,7 @@ func (h *AISettingsHandler) HandleDeleteGuestNote(w http.ResponseWriter, r *http
NoteID string `json:"note_id"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -4520,7 +4520,7 @@ func (h *AISettingsHandler) HandleImportGuestKnowledge(w http.ResponseWriter, r
Merge bool `json:"merge"` // If true, add to existing notes; if false, replace
}
if err := json.NewDecoder(r.Body).Decode(&importData); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<20)).Decode(&importData); err != nil {
http.Error(w, "Invalid import data", http.StatusBadRequest)
return
}
@@ -4622,7 +4622,7 @@ func (h *AISettingsHandler) HandleClearGuestKnowledge(w http.ResponseWriter, r *
Confirm bool `json:"confirm"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -4779,7 +4779,7 @@ func (h *AISettingsHandler) HandleInvestigateAlert(w http.ResponseWriter, r *htt
// Parse request
r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
var req AIInvestigateAlertRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -6052,7 +6052,7 @@ func (h *AISettingsHandler) HandleForcePatrol(w http.ResponseWriter, r *http.Req
// (consistent with automatic scoped runs) but still honour readiness above.
var scopedReq manualScopedPatrolRequest
if r.Body != nil {
decoder := json.NewDecoder(r.Body)
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
decoder.DisallowUnknownFields()
decodeErr := decoder.Decode(&scopedReq)
if decodeErr == nil {
@@ -6209,7 +6209,7 @@ func (h *AISettingsHandler) HandlePatrolPreflight(w http.ResponseWriter, r *http
// allowed and means "use the configured Patrol provider+model".
var body aiPatrolPreflightRequest
if r.ContentLength > 0 {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&body); err != nil {
http.Error(w, `{"error":"Invalid JSON body"}`, http.StatusBadRequest)
return
}
@@ -6367,7 +6367,7 @@ func (h *AISettingsHandler) HandlePatrolModelReadiness(w http.ResponseWriter, r
var body aiPatrolPreflightRequest
if r.ContentLength > 0 {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&body); err != nil {
http.Error(w, `{"error":"Invalid JSON body"}`, http.StatusBadRequest)
return
}
@@ -6420,7 +6420,7 @@ func (h *AISettingsHandler) HandleAcknowledgeFinding(w http.ResponseWriter, r *h
var req struct {
FindingID string `json:"finding_id"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
writeFindingInvalidRequestResponse(w, "Invalid request body", nil)
return
}
@@ -6535,7 +6535,7 @@ func (h *AISettingsHandler) HandleSnoozeFinding(w http.ResponseWriter, r *http.R
FindingID string `json:"finding_id"`
DurationHours int `json:"duration_hours"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
writeFindingInvalidRequestResponse(w, "Invalid request body", nil)
return
}
@@ -6662,7 +6662,7 @@ func (h *AISettingsHandler) HandleResolveFinding(w http.ResponseWriter, r *http.
FindingID string `json:"finding_id"`
ResolutionNote string `json:"resolution_note"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
writeFindingInvalidRequestResponse(w, "Invalid request body", nil)
return
}
@@ -6761,7 +6761,7 @@ func (h *AISettingsHandler) HandleSetFindingNote(w http.ResponseWriter, r *http.
FindingID string `json:"finding_id"`
Note string `json:"note"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -6818,7 +6818,7 @@ func (h *AISettingsHandler) HandleDismissFinding(w http.ResponseWriter, r *http.
Reason string `json:"reason"` // "not_an_issue", "expected_behavior", "will_fix_later"
Note string `json:"note"` // Optional freeform note
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
writeFindingInvalidRequestResponse(w, "Invalid request body", nil)
return
}
@@ -6970,7 +6970,7 @@ func (h *AISettingsHandler) HandleSuppressFinding(w http.ResponseWriter, r *http
var req struct {
FindingID string `json:"finding_id"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -7505,7 +7505,7 @@ func (h *AISettingsHandler) HandleAddSuppressionRule(w http.ResponseWriter, r *h
Description string `json:"description"` // Required - user's reason
AllowBroadScope bool `json:"allow_broad_scope"` // Required when resource or category is intentionally wildcarded
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -7971,7 +7971,7 @@ func (h *AISettingsHandler) HandleDenyCommand(w http.ResponseWriter, r *http.Req
Reason string `json:"reason"`
}
if r.Body != nil {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&body); err != nil {
log.Warn().Err(err).Msg("Failed to decode deny request body")
}
}
@@ -8486,7 +8486,7 @@ func (h *AISettingsHandler) HandleUpdatePatrolAutonomyMonitorOnly(w http.Respons
}
var req PatrolAutonomySettings
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", nil)
return
}
+169
View File
@@ -0,0 +1,169 @@
package api
import (
"context"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
// Token scopes do not bind sessions, so the requests that change alert policy
// or Patrol's standing suppression need a manager as well. A proxy user outside
// the admin role keeps the reads and the per-alert and per-finding actions.
func TestAlertAndPatrolPolicyRoutesRefuseProxyNonAdmin(t *testing.T) {
router := newProxyAuthRouter(t)
request := func(method, path, body, roles string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("X-Proxy-Secret", "proxy-secret")
req.Header.Set("X-Proxy-User", "someone")
req.Header.Set("X-Proxy-Roles", roles)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
return rec
}
for _, tc := range []struct {
method, path, body string
policy bool
}{
{http.MethodPut, "/api/alerts/config", `{"enabled":false}`, true},
{http.MethodPut, "/api/alerts/deadman/config", `{"pingUrl":""}`, true},
{http.MethodPut, "/api/alerts/intent-policies", `{}`, true},
{http.MethodPost, "/api/alerts/activate", `{}`, true},
{http.MethodDelete, "/api/alerts/history", ``, true},
{http.MethodPost, "/api/ai/patrol/suppressions", `{"description":"quiet","allow_broad_scope":true}`, true},
{http.MethodDelete, "/api/ai/patrol/suppressions/rule_any__1", ``, true},
{http.MethodPost, "/api/ai/patrol/suppress", `{"finding_id":"f-1"}`, true},
{http.MethodDelete, "/api/ai/patrol/findings?confirm=true", ``, true},
{http.MethodGet, "/api/alerts/config", ``, false},
{http.MethodGet, "/api/alerts/deadman/config", ``, false},
{http.MethodGet, "/api/alerts/intent-policies", ``, false},
{http.MethodGet, "/api/alerts/history", ``, false},
{http.MethodPost, "/api/alerts/acknowledge", `{}`, false},
{http.MethodPost, "/api/alerts/snooze", `{}`, false},
{http.MethodPost, "/api/alerts/clear", `{}`, false},
{http.MethodPost, "/api/alerts/incidents/note", `{}`, false},
{http.MethodGet, "/api/ai/patrol/suppressions", ``, false},
{http.MethodDelete, "/api/ai/patrol/suppressions/finding_f-1", ``, false},
} {
viewer := request(tc.method, tc.path, tc.body, "viewer|user")
if refused := viewer.Code == http.StatusForbidden; refused != tc.policy {
t.Errorf("non-admin %s %s = %d, refused = %v, want %v: %s", tc.method, tc.path, viewer.Code, refused, tc.policy, viewer.Body.String())
}
if admin := request(tc.method, tc.path, tc.body, "viewer|admin"); admin.Code == http.StatusForbidden || admin.Code == http.StatusUnauthorized {
t.Errorf("admin %s %s = %d, want the handler to answer: %s", tc.method, tc.path, admin.Code, admin.Body.String())
}
}
}
// Alert policy is the request organization's own, so its managers change it in
// a session and its viewers do not; a token bound to it is still judged by the
// scope alone.
func TestAlertPolicyRoutesAdmitRequestOrganizationManagers(t *testing.T) {
SetMultiTenantEnabled(true)
t.Cleanup(func() { SetMultiTenantEnabled(false) })
t.Setenv("PULSE_DEV", "true")
hashed, err := internalauth.HashPassword("Password!1")
if err != nil {
t.Fatalf("hash password: %v", err)
}
const writeToken = "alert-policy-write.12345678"
writer := newTokenRecord(t, writeToken, []string{config.ScopeMonitoringWrite}, nil)
writer.OrgID = "org-a"
cfg := newTestConfigWithTokens(t, writer)
cfg.AuthUser, cfg.AuthPass = "platform-admin", hashed
mtp := config.NewMultiTenantPersistence(cfg.DataPath)
if err := mtp.SaveOrganization(&models.Organization{
ID: "org-a",
DisplayName: "Org A",
OwnerUserID: "org-owner",
Members: []models.OrganizationMember{
{UserID: "org-owner", Role: models.OrgRoleOwner, AddedAt: time.Now()},
{UserID: "org-viewer", Role: models.OrgRoleViewer, AddedAt: time.Now()},
},
}); err != nil {
t.Fatalf("save organization: %v", err)
}
monitors := monitoring.NewMultiTenantMonitor(cfg, mtp, nil)
t.Cleanup(monitors.Stop)
router := newTestRouter(t, cfg, nil, monitors, nil, nil, "1.0.0")
saveConfig := func(user, token string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPut, "/api/alerts/config", strings.NewReader(`{"enabled":true}`))
req.Header.Set("X-Pulse-Org-ID", "org-a")
if token != "" {
req.Header.Set("X-API-Token", token)
} else {
session := "alert-policy-" + user + "-" + strconv.FormatInt(time.Now().UnixNano(), 10)
GetSessionStore().CreateSession(session, time.Hour, "agent", "127.0.0.1", user)
req.Header.Set("X-CSRF-Token", generateCSRFToken(session))
req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: session})
}
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
return rec
}
for _, tc := range []struct {
user, token string
status int
}{
{"org-owner", "", http.StatusOK},
{"org-viewer", "", http.StatusForbidden},
{"", writeToken, http.StatusOK},
} {
if rec := saveConfig(tc.user, tc.token); rec.Code != tc.status {
t.Fatalf("user %q token %q alert config save = %d, want %d: %s", tc.user, tc.token, rec.Code, tc.status, rec.Body.String())
}
}
}
type alertOperatorAuthorizer struct{}
func (alertOperatorAuthorizer) Authorize(ctx context.Context, action, resource string) (bool, error) {
return internalauth.GetUser(ctx) == "operator" && action == internalauth.ActionWrite && resource == internalauth.ResourceAlerts, nil
}
// With a real RBAC authorizer, the grant the built-in operator role carries
// (write on alerts) admits a user who is not an administrator to alert policy.
// It does not reach Patrol's suppression rules, and a viewer stays refused.
func TestAlertPolicyRoutesAdmitRBACAlertWriteGrant(t *testing.T) {
previous := internalauth.GetAuthorizer()
internalauth.SetAuthorizer(alertOperatorAuthorizer{})
t.Cleanup(func() { internalauth.SetAuthorizer(previous) })
router := newProxyAuthRouter(t)
for _, tc := range []struct {
user, method, path, body string
refused bool
}{
{"operator", http.MethodPut, "/api/alerts/config", `{"enabled":false}`, false},
{"operator", http.MethodDelete, "/api/alerts/history", ``, false},
{"operator", http.MethodPost, "/api/ai/patrol/suppressions", `{"description":"quiet","allow_broad_scope":true}`, true},
{"viewer", http.MethodPut, "/api/alerts/config", `{"enabled":false}`, true},
{"viewer", http.MethodDelete, "/api/alerts/history", ``, true},
} {
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
req.Header.Set("X-Proxy-Secret", "proxy-secret")
req.Header.Set("X-Proxy-User", tc.user)
req.Header.Set("X-Proxy-Roles", "user")
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if refused := rec.Code == http.StatusForbidden; refused != tc.refused {
t.Errorf("%s %s %s = %d, refused = %v, want %v: %s", tc.user, tc.method, tc.path, rec.Code, refused, tc.refused, rec.Body.String())
}
}
}
+3 -3
View File
@@ -1232,7 +1232,7 @@ func (r alertIdentifiersRequest) identifiers() []string {
// POST /api/alerts/acknowledge with {"alertIdentifier": "alert-id"}
func (h *AlertHandlers) AcknowledgeAlertByBody(w http.ResponseWriter, r *http.Request) {
var req alertIdentifierRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(&req); err != nil {
log.Error().Err(err).Msg("Failed to decode acknowledge request body")
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
@@ -1286,7 +1286,7 @@ func (h *AlertHandlers) AcknowledgeAlertByBody(w http.ResponseWriter, r *http.Re
// POST /api/alerts/unacknowledge with {"alertIdentifier": "alert-id"}
func (h *AlertHandlers) UnacknowledgeAlertByBody(w http.ResponseWriter, r *http.Request) {
var req alertIdentifierRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(&req); err != nil {
log.Error().Err(err).Msg("Failed to decode unacknowledge request body")
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
@@ -1414,7 +1414,7 @@ func (h *AlertHandlers) UnsnoozeAlertByBody(w http.ResponseWriter, r *http.Reque
// POST /api/alerts/clear with {"alertIdentifier": "alert-id"}
func (h *AlertHandlers) ClearAlertByBody(w http.ResponseWriter, r *http.Request) {
var req alertIdentifierRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(&req); err != nil {
log.Error().Err(err).Msg("Failed to decode clear request body")
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
+14
View File
@@ -1370,6 +1370,20 @@ func TestAlertHandlers_ErrorCases(t *testing.T) {
assert.Equal(t, 400, w.Code)
})
t.Run("ByBody_OversizedBody", func(t *testing.T) {
body := `{"alertIdentifier": "a1", "padding": "` + strings.Repeat("a", 16<<10) + `"}`
for path, handler := range map[string]http.HandlerFunc{
"/api/alerts/acknowledge": h.AcknowledgeAlertByBody,
"/api/alerts/unacknowledge": h.UnacknowledgeAlertByBody,
"/api/alerts/clear": h.ClearAlertByBody,
} {
req := httptest.NewRequest("POST", path, strings.NewReader(body))
w := httptest.NewRecorder()
handler(w, req)
assert.Equal(t, 400, w.Code, path)
}
})
t.Run("AcknowledgeAlertByBody_MissingID", func(t *testing.T) {
req := httptest.NewRequest("POST", "/api/alerts/acknowledge", strings.NewReader(`{"alertIdentifier": ""}`))
w := httptest.NewRecorder()
+25
View File
@@ -27,3 +27,28 @@ func apiTokenAuthenticatedUser(record *config.APITokenRecord) string {
}
return fmt.Sprintf("token:%s", strings.TrimSpace(record.ID))
}
// apiTokenActsForOwner reports whether a token stands in for the person who
// owns it rather than for a machine: it names a human owner and holds a scope
// that lets a phone, an Assistant client or an action reviewer act in that
// owner's name. Agent, runner and plain monitoring or settings credentials
// record who issued them but belong to the machine or integration they were
// issued for.
func apiTokenActsForOwner(record *config.APITokenRecord) bool {
if apiTokenBoundUser(record) == "" {
return false
}
for _, scope := range []string{
config.ScopeRelayMobileAccess,
config.ScopeAIChat,
config.ScopeAIExecute,
config.ScopeActionsPlan,
config.ScopeActionsApprove,
config.ScopeActionsExecute,
} {
if record.HasScope(scope) {
return true
}
}
return false
}
+65
View File
@@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
@@ -467,6 +468,70 @@ func TestAttentionLifecycleMutationsRefreshTheCanonicalProjection(t *testing.T)
}
}
func TestAttentionSuppressionReasonIsBounded(t *testing.T) {
now := time.Now().UTC()
alert := attentionHandlerAlert(
"agent:node-1/disk:mnt-disk2::metric-threshold:disk",
operationaltrust.OperationalOpen,
now,
)
manager := alerts.NewManagerWithDataDir(t.TempDir())
t.Cleanup(manager.Stop)
setUnexportedField(
t,
manager,
"activeAlerts",
map[string]*alerts.Alert{alert.ID: alert.Clone()},
)
setUnexportedField(
t,
manager,
"activeAlertAlias",
map[string]string{alert.OperationalRecord.ID: alert.ID},
)
monitor := &monitoring.Monitor{}
setUnexportedField(t, monitor, "state", models.NewState())
setUnexportedField(t, monitor, "alertManager", manager)
handler := NewAttentionHandlers(
func(context.Context) *monitoring.Monitor { return monitor },
nil,
)
suppress := func(reason string) *httptest.ResponseRecorder {
body, err := json.Marshal(map[string]string{
"reason": reason,
"expiresAt": now.Add(time.Hour).Format(time.RFC3339Nano),
})
if err != nil {
t.Fatalf("encode suppression: %v", err)
}
response := httptest.NewRecorder()
handler.HandleAttention(response, httptest.NewRequest(
http.MethodPost,
"/api/ai/patrol/attention/agent:node-1/disk:mnt-disk2::metric-threshold:disk/suppress",
bytes.NewReader(body),
))
return response
}
oversized := strings.Repeat("<", alerts.MaxOperationalSuppressionReasonRunes+1)
if response := suppress(oversized); response.Code != http.StatusBadRequest ||
!strings.Contains(response.Body.String(), "invalid_attention_suppression") {
t.Fatalf("oversized reason status = %d: %s", response.Code, response.Body.String())
}
if active := manager.GetActiveAlerts(); len(active) != 1 ||
active[0].OperationalRecord.State != operationaltrust.OperationalOpen ||
active[0].OperationalRecord.Suppression != nil {
t.Fatalf("rejected suppression changed the alert: %+v", active)
}
// The bound counts characters, and surrounding whitespace is not stored.
boundary := strings.Repeat("日", alerts.MaxOperationalSuppressionReasonRunes)
if response := suppress(" " + boundary + " "); response.Code != http.StatusOK {
t.Fatalf("boundary reason status = %d: %s", response.Code, response.Body.String())
}
assertAttentionHandlerState(t, handler, alert.ID, operationaltrust.OperationalSuppressed)
}
func assertAttentionHandlerState(
t *testing.T,
handler *AttentionHandlers,
+7 -3
View File
@@ -6,7 +6,9 @@ import (
"net/url"
"strings"
"time"
"unicode/utf8"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/utils"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
@@ -108,7 +110,9 @@ func (h *AttentionHandlers) handleAttentionMutation(
return
}
now := time.Now().UTC()
if strings.TrimSpace(request.Reason) == "" ||
reason := strings.TrimSpace(request.Reason)
if reason == "" ||
utf8.RuneCountInString(reason) > alerts.MaxOperationalSuppressionReasonRunes ||
request.ExpiresAt.IsZero() ||
!request.ExpiresAt.After(now) ||
request.ExpiresAt.After(now.Add(maxAttentionSuppressionDuration)) {
@@ -116,7 +120,7 @@ func (h *AttentionHandlers) handleAttentionMutation(
w,
http.StatusBadRequest,
"invalid_attention_suppression",
"Suppression requires a reason and an expiry within 30 days.",
"Suppression requires a reason of at most 240 characters and an expiry within 30 days.",
)
return
}
@@ -124,7 +128,7 @@ func (h *AttentionHandlers) handleAttentionMutation(
err = manager.SuppressOperationalAlert(
itemID,
actor,
request.Reason,
reason,
&expiresAt,
)
case attentionMutationUnsuppress:
@@ -38,6 +38,71 @@ func TestAuditEndpointsRequireAuditReadScope(t *testing.T) {
}
}
func TestRBACEndpointsRequireFullAccessScope(t *testing.T) {
t.Setenv("PULSE_DEV", "true")
cases := []struct {
method string
path string
body string
}{
{method: http.MethodGet, path: "/api/admin/roles", body: ""},
{method: http.MethodPost, path: "/api/admin/roles", body: `{"id":"role-1","name":"Role 1"}`},
{method: http.MethodPut, path: "/api/admin/roles/role-1", body: `{"id":"role-1","name":"Role 1"}`},
{method: http.MethodDelete, path: "/api/admin/roles/role-1", body: ""},
{method: http.MethodGet, path: "/api/admin/users", body: ""},
{method: http.MethodGet, path: "/api/admin/users/alice/permissions", body: ""},
{method: http.MethodPut, path: "/api/admin/users/alice/roles", body: `{"roleIds":["admin"]}`},
{method: http.MethodDelete, path: "/api/admin/users/alice", body: ""},
{method: http.MethodGet, path: "/api/admin/rbac/integrity", body: ""},
{method: http.MethodPost, path: "/api/admin/rbac/reset-admin", body: `{}`},
}
// An agent install token and the widest settings token both stop short of
// full access, so neither may read or change who administers the instance.
for name, scopes := range map[string][]string{
"agent": {config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeDockerReport, config.ScopeKubernetesReport},
"settings": {config.ScopeSettingsRead, config.ScopeSettingsWrite},
} {
t.Run(name, func(t *testing.T) {
rawToken := "rbac-scope-" + name + "-token-123.12345678"
record := newTokenRecord(t, rawToken, scopes, nil)
cfg := newTestConfigWithTokens(t, record)
router := newTestRouter(t, cfg, nil, nil, nil, nil, "1.0.0")
for _, tc := range cases {
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
req.Header.Set("X-API-Token", rawToken)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("expected 403 for missing full-access scope on %s %s, got %d", tc.method, tc.path, rec.Code)
}
if !strings.Contains(rec.Body.String(), `"requiredScope":"`+config.ScopeWildcard+`"`) {
t.Fatalf("expected missing scope response to name %q on %s %s, got %q", config.ScopeWildcard, tc.method, tc.path, rec.Body.String())
}
}
})
}
t.Run("full access", func(t *testing.T) {
rawToken := "rbac-scope-full-access-token-123.12345678"
record := newTokenRecord(t, rawToken, []string{config.ScopeWildcard}, nil)
cfg := newTestConfigWithTokens(t, record)
router := newTestRouter(t, cfg, nil, nil, nil, nil, "1.0.0")
for _, path := range []string{"/api/admin/roles", "/api/admin/users"} {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Header.Set("X-API-Token", rawToken)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200 for a full-access token on %s, got %d %q", path, rec.Code, rec.Body.String())
}
}
})
}
func TestReportingEndpointsRequireSettingsReadScope(t *testing.T) {
t.Setenv("PULSE_DEV", "true")
+64 -23
View File
@@ -594,6 +594,19 @@ func validateAPITokenAgainstConfigsLocked(globalCfg, targetCfg *config.Config, t
return validateAPITokenLocked(globalCfg, token)
}
// tenantMonitorOutsideConfigLock requires config.Mu.RLock and returns with it
// held again. Resolving a cold tenant constructs its monitor, which waits for
// that tenant's connections and for the manager's settings lock. Holding
// config.Mu across that wait stalls every request behind the first queued
// token writer, and deadlocks against a settings save, which takes config.Mu
// while holding the settings lock. Callers must recheck the owner after
// validating against the returned monitor's config.
func tenantMonitorOutsideConfigLock(mtm *monitoring.MultiTenantMonitor, orgID string) (*monitoring.Monitor, error) {
config.Mu.RUnlock()
defer config.Mu.RLock()
return mtm.GetMonitor(orgID)
}
// CheckProxyAuth validates proxy authentication headers
func CheckProxyAuth(cfg *config.Config, r *http.Request) (bool, string, bool) {
// Check if proxy auth is configured
@@ -731,6 +744,14 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, write
// long-lived read. A later proxy/token/basic admission must not inherit an
// earlier session marker if middleware checks this request again.
*r = *r.WithContext(context.WithValue(r.Context(), sessionReadAdmissionKey{}, (*sessionReadAdmission)(nil)))
// Admission sees only the headers. Bind the body, which may arrive much
// later, to that same credential. Registered before config.Mu is taken, so
// it runs after the read lock below has been released.
defer func() {
if allowed {
retainRequestBodyAuthority(cfg, r)
}
}()
// Dev mode bypass for all auth (disabled by default)
if adminBypassAppliesToRequest(r) {
@@ -880,6 +901,14 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, write
if cfg.AuthUser == "" && cfg.AuthPass == "" && !cfg.HasAPITokens() && cfg.ProxyAuthSecret == "" {
if hasEnabledSSOProvidersForAuth(cfg) {
log.Debug().Msg("SSO enabled without local credentials, authentication required")
} else if hostedModeEnabledFromEnv() {
// A hosted runtime always enforces authentication, as
// configTransferAuthenticationConfigured already says. Its users
// arrive through the control plane handoff, so it holds no local
// credentials and never leaves this state through first-run setup.
// Nobody sits at its console either: its loopback peers are the
// requests this server sends for its tenants (webhooks, Apprise).
log.Debug().Msg("Hosted runtime without local credentials, authentication required")
} else {
if isDirectLoopbackRequest(r) {
anonymous = true
@@ -941,20 +970,7 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, write
if ipLocked && ipLockedUntil.After(lockedUntil) {
lockedUntil = ipLockedUntil
}
remainingMinutes := int(time.Until(lockedUntil).Minutes())
if remainingMinutes < 1 {
remainingMinutes = 1
}
log.Warn().Str("user", parts[0]).Str("ip", clientIP).Msg("Account locked out")
LogAuditEventForTenant(GetOrgID(r.Context()), "login", parts[0], clientIP, r.URL.Path, false, "Account locked")
if w != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(fmt.Sprintf(`{"error":"Account temporarily locked","message":"Too many failed attempts. Please try again in %d minutes.","lockedUntil":"%s"}`,
remainingMinutes, lockedUntil.Format(time.RFC3339))))
}
writeBasicAuthLockedOut(w, r, parts[0], clientIP, lockedUntil)
return false
}
cfgAuthUser, cfgAuthPass := snapshotLocalAuthCredentialsLocked(cfg)
@@ -968,11 +984,17 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, write
Bool("pass_match", passMatch).
Msg("Auth check")
if userMatch && passMatch {
// Clear failed login attempts
ClearFailedLogins(parts[0])
ClearFailedLogins(GetClientIP(r))
// The lockout check above ran before the password was
// hashed, so attempts sent together all passed it. Count
// this one in the same step that asks whether the limit
// was reached meanwhile: if it was, the attempt is refused
// whatever its result. A success clears the failed attempts.
if lockedUntil, locked := RecordLoginAttempt(userMatch && passMatch, parts[0], clientIP); locked {
writeBasicAuthLockedOut(w, r, parts[0], clientIP, lockedUntil)
return false
}
if userMatch && passMatch {
// TenantMiddleware admitted this request's organization
// before these credentials were verified, so it could not
// apply the organization access policy to this principal.
@@ -1022,9 +1044,7 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, write
w.Header().Set("X-Auth-Method", "basic")
return true
} else {
// Failed login
RecordFailedLogin(parts[0])
RecordFailedLogin(clientIP)
// Failed login, counted by RecordLoginAttempt above
LogAuditEventForTenant(GetOrgID(r.Context()), "login", parts[0], clientIP, r.URL.Path, false, "Invalid credentials")
// Get updated attempt counts
@@ -1063,6 +1083,24 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, write
return false
}
// writeBasicAuthLockedOut refuses a Basic sign-in for a username or address
// that has used up its failed attempts.
func writeBasicAuthLockedOut(w http.ResponseWriter, r *http.Request, username, clientIP string, lockedUntil time.Time) {
remainingMinutes := int(time.Until(lockedUntil).Minutes())
if remainingMinutes < 1 {
remainingMinutes = 1
}
log.Warn().Str("user", username).Str("ip", clientIP).Msg("Account locked out")
LogAuditEventForTenant(GetOrgID(r.Context()), "login", username, clientIP, r.URL.Path, false, "Account locked")
if w != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(fmt.Sprintf(`{"error":"Account temporarily locked","message":"Too many failed attempts. Please try again in %d minutes.","lockedUntil":"%s"}`,
remainingMinutes, lockedUntil.Format(time.RFC3339))))
}
}
// RequireAuth middleware checks for authentication
func RequireAuth(cfg *config.Config, handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
@@ -1419,7 +1457,10 @@ func extractAndStoreAuthContext(cfg *config.Config, mtm *monitoring.MultiTenantM
}
}
if mtm != nil {
// A tenant inventory is consulted only for an explicit token. A request
// without one must not resolve, and so possibly start, the monitor of
// whichever organization it names.
if mtm != nil && explicitTokenProvided {
// Check for Tenant ID in header or cookie
orgID := "default"
if headerOrgID := r.Header.Get("X-Pulse-Org-ID"); headerOrgID != "" {
@@ -1432,7 +1473,7 @@ func extractAndStoreAuthContext(cfg *config.Config, mtm *monitoring.MultiTenantM
if orgID != "default" {
// Prevent DoS: Check if org exists before loading (which triggers directory creation)
if mtm.OrgExists(orgID) {
if m, err := mtm.GetMonitor(orgID); err == nil && m != nil {
if m, err := tenantMonitorOutsideConfigLock(mtm, orgID); err == nil && m != nil {
targetConfig = m.GetConfig()
targetOrgID = strings.TrimSpace(orgID)
}
+56
View File
@@ -390,3 +390,59 @@ func TestAuthContextMiddlewareUsesCurrentTenantManager(t *testing.T) {
})
}
}
// The auth context runs for every request before any credential is enforced.
// It must not start the tenant a request merely names, and a token request
// that does need a cold tenant's inventory must not hold config.Mu while that
// tenant starts: every token check queues as a writer behind that reader, and
// a settings save takes config.Mu under the lock the start is waiting for.
func TestExtractAndStoreAuthContextResolvesColdTenantOutsideConfigLock(t *testing.T) {
const orgID = "starting"
dir := t.TempDir()
mtp := config.NewMultiTenantPersistence(dir)
if _, err := mtp.GetPersistence(orgID); err != nil {
t.Fatal(err)
}
cfg := &config.Config{DataPath: dir, ConfigPath: dir}
manager := monitoring.NewMultiTenantMonitor(cfg, mtp, nil)
t.Cleanup(manager.Stop)
starts, startsUnderConfigLock := 0, 0
manager.SetMonitorInitializer(func(*monitoring.Monitor) {
starts++
writer := make(chan struct{})
go func() {
config.Mu.Lock()
close(writer)
config.Mu.Unlock()
}()
select {
case <-writer:
case <-time.After(2 * time.Second):
startsUnderConfigLock++
}
})
newRequest := func(token string) *http.Request {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-Pulse-Org-ID", orgID)
if token != "" {
req.Header.Set("X-API-Token", token)
}
return req
}
extractAndStoreAuthContext(cfg, manager, newRequest(""))
if _, started := manager.PeekMonitor(orgID); started || starts != 0 {
t.Fatal("a request without credentials started the tenant it named")
}
req := extractAndStoreAuthContext(cfg, manager, newRequest("unknown-token-123.12345678"))
if internalauth.GetUser(req.Context()) != "" || internalauth.GetAPIToken(req.Context()) != nil {
t.Fatal("unknown token must not receive user or API token context")
}
if _, started := manager.PeekMonitor(orgID); !started || starts != 1 {
t.Fatalf("tenant token inventory was not resolved (starts = %d)", starts)
}
if startsUnderConfigLock != 0 {
t.Fatal("config.Mu was held while the tenant monitor started")
}
}
+161 -6
View File
@@ -3,29 +3,123 @@ package api
import (
"crypto/sha256"
"encoding/base64"
"encoding/xml"
"errors"
"fmt"
"strings"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
"github.com/rs/zerolog/log"
)
// ssoPrincipalNamespace prefixes every principal minted by stableSSOPrincipal.
const ssoPrincipalNamespace = "sso:"
// ssoUnknownOriginalIssuerSentinel is recorded when a provider entry is edited
// or deleted while its original issuer cannot be determined, forcing subsequent
// logins on that entry ID to fail closed into issuer-scoped principals.
const ssoUnknownOriginalIssuerSentinel = "__unknown__"
func stableSSOPrincipal(providerType config.SSOProviderType, providerID string, subject string) (string, error) {
return ssoPrincipalWithOptionalIssuer(providerType, providerID, "", subject)
}
func stableSSOPrincipalWithIssuer(providerType config.SSOProviderType, providerID string, issuer string, subject string) (string, error) {
iss := strings.TrimSpace(issuer)
if iss == "" {
return "", fmt.Errorf("sso issuer is required")
}
return ssoPrincipalWithOptionalIssuer(providerType, providerID, iss, subject)
}
func ssoPrincipalWithOptionalIssuer(providerType config.SSOProviderType, providerID string, issuer string, subject string) (string, error) {
typ := strings.TrimSpace(strings.ToLower(string(providerType)))
id := strings.TrimSpace(providerID)
sub := strings.TrimSpace(subject)
if typ == "" {
return "", fmt.Errorf("sso provider type is required")
}
if id == "" {
return "", fmt.Errorf("sso provider id is required")
}
if sub == "" {
trimmed := strings.TrimSpace(subject)
if trimmed == "" {
return "", fmt.Errorf("sso subject is required")
}
// The provider identifies an account by the exact subject, so "alice" and
// "alice\u00a0" are two accounts. Refuse a padded subject instead of
// normalizing it onto the principal of the account it resembles.
if trimmed != subject {
return "", fmt.Errorf("sso subject must not have leading or trailing whitespace")
}
sum := sha256.Sum256([]byte(typ + "\x00" + id + "\x00" + sub))
return "sso:" + typ + ":" + id + ":" + base64.RawURLEncoding.EncodeToString(sum[:]), nil
scoped := typ + "\x00" + id + "\x00"
if iss := strings.TrimSpace(issuer); iss != "" {
scoped += iss + "\x00"
}
sum := sha256.Sum256([]byte(scoped + subject))
return ssoPrincipalNamespace + typ + ":" + id + ":" + base64.RawURLEncoding.EncodeToString(sum[:]), nil
}
// stableSSOPrincipalForIssuer derives the stable principal for an SSO login
// while preventing issuer changes on an existing provider entry ID from
// handing saved roles to another identity provider's subjects. The first
// issuer bound to (providerType, providerID) keeps the compatibility principal
// format so upgrades do not rename existing users; any other issuer hashes the
// issuer into the principal.
func stableSSOPrincipalForIssuer(manager internalauth.Manager, providerType config.SSOProviderType, providerID string, issuer string, subject string) (string, error) {
iss := strings.TrimSpace(issuer)
if iss == "" {
return "", fmt.Errorf("sso issuer is required")
}
if registry, ok := manager.(internalauth.ProviderIssuerRegistry); ok {
originalIssuer, err := registry.GetOrBindProviderOriginalIssuer(string(providerType), providerID, iss)
if err != nil {
return "", fmt.Errorf("resolve sso provider issuer binding: %w", err)
}
if originalIssuer != iss {
return stableSSOPrincipalWithIssuer(providerType, providerID, iss, subject)
}
}
return stableSSOPrincipal(providerType, providerID, subject)
}
// isStableSSOPrincipal reports whether value lies in the namespace reserved
// for stableSSOPrincipal. Such a value names a current SSO identity, possibly
// another provider's, and is never a pre-principal username or email.
func isStableSSOPrincipal(value string) bool {
return strings.HasPrefix(strings.ToLower(strings.TrimSpace(value)), ssoPrincipalNamespace)
}
func extractSAMLEntityIDFromXML(rawXML string) string {
trimmed := strings.TrimSpace(rawXML)
if trimmed == "" {
return ""
}
var descriptor struct {
EntityID string `xml:"entityID,attr"`
}
if err := xml.Unmarshal([]byte(trimmed), &descriptor); err != nil {
return ""
}
return strings.TrimSpace(descriptor.EntityID)
}
func bindSSOProviderOriginalIssuer(manager internalauth.Manager, providerType config.SSOProviderType, providerID string, issuer string, failClosedIfUnknown bool) {
registry, ok := manager.(internalauth.ProviderIssuerRegistry)
if !ok {
return
}
iss := strings.TrimSpace(issuer)
if iss == "" {
if !failClosedIfUnknown {
return
}
iss = ssoUnknownOriginalIssuerSentinel
}
if err := registry.BindProviderOriginalIssuer(string(providerType), providerID, iss); err != nil {
log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to bind original issuer for SSO provider")
}
}
func ssoLegacyPrincipalCandidates(values ...string) []string {
@@ -52,6 +146,11 @@ func ssoLegacyPrincipalCandidates(values ...string) []string {
return candidates
}
// errSSORolesNotReplaced reports that an authoritative group mapping could not
// replace the principal's saved roles. Callers must refuse the sign-in rather
// than continue with grants from an earlier one.
var errSSORolesNotReplaced = errors.New("sso role assignments could not be replaced")
func applySSORoleAssignments(manager internalauth.Manager, principal string, legacyCandidates []string, mappedRoles []string, mappingAuthoritative bool, ensureListed bool) error {
principal = strings.TrimSpace(principal)
if manager == nil || principal == "" {
@@ -59,15 +158,60 @@ func applySSORoleAssignments(manager internalauth.Manager, principal string, leg
}
if mappingAuthoritative || len(mappedRoles) > 0 {
return manager.UpdateUserRoles(principal, mappedRoles)
err := updateMappedSSORoles(manager, principal, mappedRoles)
if err == nil || !mappingAuthoritative {
return err
}
// The store replaces a role list completely or not at all, so a mapping
// that names a missing role leaves the previous sign-in's roles saved.
// Such a group resolves to no role: replace the saved roles with the
// mapped roles that exist instead of letting stale grants outlive the
// group membership that justified them.
existing := make([]string, 0, len(mappedRoles))
errorAwareReader, hasErrorAwareReader := manager.(internalauth.ErrorAwareRoleReader)
for _, roleID := range mappedRoles {
if hasErrorAwareReader {
_, ok, readErr := errorAwareReader.GetRoleWithError(roleID)
if readErr != nil {
return errors.Join(errSSORolesNotReplaced, err, readErr)
}
if ok {
existing = append(existing, roleID)
}
continue
}
if _, ok := manager.GetRole(roleID); ok {
existing = append(existing, roleID)
}
}
if len(existing) == len(mappedRoles) {
return errors.Join(errSSORolesNotReplaced, err)
}
if replaceErr := updateMappedSSORoles(manager, principal, existing); replaceErr != nil {
return errors.Join(errSSORolesNotReplaced, err, replaceErr)
}
return fmt.Errorf("assigned only the mapped roles that exist %q: %w", existing, err)
}
principalAssignment, principalExists := manager.GetUserAssignment(principal)
if principalExists && principalAssignment.RolesFromMapping {
// The provider no longer maps groups to roles. Roles an earlier mapping
// saved are not an administrator's assignment and must not outlive it,
// so only roles assigned by hand are kept below.
if err := manager.UpdateUserRoles(principal, nil); err != nil {
return err
}
principalAssignment.RoleIDs = nil
}
principalHasRoles := principalExists && len(principalAssignment.RoleIDs) > 0
for _, candidate := range legacyCandidates {
candidate = strings.TrimSpace(candidate)
if candidate == "" || candidate == principal {
// Candidates are claim text the signing-in user may control. Only a
// pre-principal alias may migrate: legacy and canonical rows share one
// key space, so a candidate in the stable principal namespace would
// select another SSO user's live assignment.
if candidate == "" || candidate == principal || isStableSSOPrincipal(candidate) {
continue
}
assignment, ok := manager.GetUserAssignment(candidate)
@@ -92,6 +236,17 @@ func applySSORoleAssignments(manager internalauth.Manager, principal string, leg
return nil
}
// updateMappedSSORoles replaces the principal's roles with the result of the
// provider's group role mapping. Durable managers record that origin so the
// roles can be withdrawn when the mapping is removed; managers predating it
// remain compatible.
func updateMappedSSORoles(manager internalauth.Manager, principal string, mappedRoles []string) error {
if mapped, ok := manager.(internalauth.MappedRoleManager); ok {
return mapped.UpdateUserRolesFromMapping(principal, mappedRoles)
}
return manager.UpdateUserRoles(principal, mappedRoles)
}
// recordSSOIdentity keeps mutable presentation claims separate from the
// provider-scoped authorization principal. Managers predating identity
// metadata remain compatible; durable managers implement UserIdentityManager.
@@ -1,6 +1,7 @@
package api
import (
"errors"
"strings"
"testing"
@@ -194,3 +195,221 @@ func TestApplySSORoleAssignmentsRejectsConflictingLegacySQLiteAlias(t *testing.T
t.Fatalf("legacy assignment changed before conflict resolution: %#v, exists=%v", legacy, ok)
}
}
func TestApplySSORoleAssignmentsWithdrawsMappedRolesWhenMappingIsRemoved(t *testing.T) {
manager, err := auth.NewSQLiteManager(auth.SQLiteManagerConfig{DataDir: t.TempDir()})
if err != nil {
t.Fatalf("NewSQLiteManager: %v", err)
}
defer manager.Close()
mapped := "sso:oidc:okta:mapped"
manual := "sso:oidc:okta:manual"
// While the provider maps groups, sign-in saves the mapped role.
if err := applySSORoleAssignments(manager, mapped, nil, []string{auth.RoleAdmin}, true, true); err != nil {
t.Fatalf("mapped sign-in: %v", err)
}
if err := manager.UpdateUserRoles(manual, []string{auth.RoleOperator}); err != nil {
t.Fatalf("seed manual assignment: %v", err)
}
// The last mapping is removed: the next sign-in is no longer authoritative.
for _, principal := range []string{mapped, manual} {
if err := applySSORoleAssignments(manager, principal, nil, nil, false, true); err != nil {
t.Fatalf("sign-in without mapping for %s: %v", principal, err)
}
}
assignment, ok := manager.GetUserAssignment(mapped)
if !ok || len(assignment.RoleIDs) != 0 || assignment.RolesFromMapping {
t.Fatalf("roles saved by a removed mapping survived: %#v, exists=%v", assignment, ok)
}
assignment, ok = manager.GetUserAssignment(manual)
if !ok || len(assignment.RoleIDs) != 1 || assignment.RoleIDs[0] != auth.RoleOperator {
t.Fatalf("manual assignment was not preserved: %#v, exists=%v", assignment, ok)
}
// Roles an administrator saves for a mapped user are theirs to keep.
if err := applySSORoleAssignments(manager, mapped, nil, []string{auth.RoleAdmin}, true, true); err != nil {
t.Fatalf("mapped sign-in: %v", err)
}
if err := manager.UpdateUserRoles(mapped, []string{auth.RoleViewer}); err != nil {
t.Fatalf("manual reassignment: %v", err)
}
if err := applySSORoleAssignments(manager, mapped, nil, nil, false, true); err != nil {
t.Fatalf("sign-in without mapping: %v", err)
}
assignment, ok = manager.GetUserAssignment(mapped)
if !ok || len(assignment.RoleIDs) != 1 || assignment.RoleIDs[0] != auth.RoleViewer {
t.Fatalf("manual reassignment was not preserved: %#v, exists=%v", assignment, ok)
}
}
func TestStableSSOPrincipalRefusesSubjectPaddedOntoAnotherAccount(t *testing.T) {
for _, providerType := range []config.SSOProviderType{config.SSOProviderTypeOIDC, config.SSOProviderTypeSAML} {
victim, err := stableSSOPrincipal(providerType, "company", "alice")
if err != nil {
t.Fatalf("stableSSOPrincipal victim: %v", err)
}
for _, subject := range []string{"alice ", " alice", "alice\t", "alice\n", "alice\u00a0", "\u2003alice", "alice\u3000", "\u00a0"} {
if principal, err := stableSSOPrincipal(providerType, "company", subject); err == nil {
t.Fatalf("%s subject %q must be refused, got principal %q (subject %q has %q)", providerType, subject, principal, "alice", victim)
}
}
spaced, err := stableSSOPrincipal(providerType, "company", "alice smith")
if err != nil {
t.Fatalf("stableSSOPrincipal interior whitespace: %v", err)
}
if spaced == victim {
t.Fatalf("%s subjects %q and %q share a principal", providerType, "alice smith", "alice")
}
}
}
func TestStableSSOPrincipalForIssuerIsolatesRepointedEntriesWithoutRenamingExisting(t *testing.T) {
manager, err := auth.NewSQLiteManager(auth.SQLiteManagerConfig{DataDir: t.TempDir()})
if err != nil {
t.Fatalf("NewSQLiteManager: %v", err)
}
defer manager.Close()
base, err := stableSSOPrincipal(config.SSOProviderTypeOIDC, "company", "2")
if err != nil {
t.Fatalf("stableSSOPrincipal: %v", err)
}
// Original issuer keeps compatibility principal format (no existing users renamed).
original, err := stableSSOPrincipalForIssuer(manager, config.SSOProviderTypeOIDC, "company", "https://old-idp.example.com", "2")
if err != nil {
t.Fatalf("stableSSOPrincipalForIssuer original: %v", err)
}
if original != base {
t.Fatalf("original issuer principal = %q, want %q", original, base)
}
// Repointing or recreating the same entry ID for another issuer yields a distinct principal.
repointed, err := stableSSOPrincipalForIssuer(manager, config.SSOProviderTypeOIDC, "company", "https://new-idp.example.com", "2")
if err != nil {
t.Fatalf("stableSSOPrincipalForIssuer repointed: %v", err)
}
if repointed == original {
t.Fatalf("repointed issuer collided with original principal %q", original)
}
// Returning to the original issuer restores the original principal.
restored, err := stableSSOPrincipalForIssuer(manager, config.SSOProviderTypeOIDC, "company", "https://old-idp.example.com", "2")
if err != nil {
t.Fatalf("stableSSOPrincipalForIssuer restored: %v", err)
}
if restored != original {
t.Fatalf("restored principal = %q, want %q", restored, original)
}
// Unknown original issuer sentinel fails closed for any real issuer.
bindSSOProviderOriginalIssuer(manager, config.SSOProviderTypeSAML, "lazy-saml", "", true)
samlBase, err := stableSSOPrincipal(config.SSOProviderTypeSAML, "lazy-saml", "2")
if err != nil {
t.Fatalf("stableSSOPrincipal saml: %v", err)
}
samlAfterEdit, err := stableSSOPrincipalForIssuer(manager, config.SSOProviderTypeSAML, "lazy-saml", "https://idp.example.com/saml", "2")
if err != nil {
t.Fatalf("stableSSOPrincipalForIssuer lazy-saml: %v", err)
}
if samlAfterEdit == samlBase {
t.Fatalf("lazy SAML entry edited with unknown issuer must fail closed, got %q", samlAfterEdit)
}
}
func TestApplySSORoleAssignmentsIgnoresStablePrincipalCandidates(t *testing.T) {
victim, err := stableSSOPrincipal(config.SSOProviderTypeOIDC, "corp", "1042")
if err != nil {
t.Fatalf("stableSSOPrincipal victim: %v", err)
}
principal, err := stableSSOPrincipal(config.SSOProviderTypeOIDC, "guests", "7")
if err != nil {
t.Fatalf("stableSSOPrincipal caller: %v", err)
}
candidates := ssoLegacyPrincipalCandidates("mallory", "mallory@guests.example", " "+victim)
t.Run("sqlite migrator", func(t *testing.T) {
manager, err := auth.NewSQLiteManager(auth.SQLiteManagerConfig{DataDir: t.TempDir()})
if err != nil {
t.Fatalf("NewSQLiteManager: %v", err)
}
defer manager.Close()
if err := manager.UpdateUserRoles(victim, []string{auth.RoleAdmin}); err != nil {
t.Fatalf("seed canonical assignment: %v", err)
}
if err := applySSORoleAssignments(manager, principal, candidates, nil, false, true); err != nil {
t.Fatalf("applySSORoleAssignments: %v", err)
}
kept, ok := manager.GetUserAssignment(victim)
if !ok || len(kept.RoleIDs) != 1 || kept.RoleIDs[0] != auth.RoleAdmin {
t.Fatalf("another principal's assignment changed: %#v, exists=%v", kept, ok)
}
if got, ok := manager.GetUserAssignment(principal); !ok || len(got.RoleIDs) != 0 {
t.Fatalf("caller assignment = %#v, exists=%v, want listed without roles", got, ok)
}
// Defense-in-depth: direct MigrateUserAssignment also refuses sso: source.
if err := manager.MigrateUserAssignment(victim, principal); err == nil {
t.Fatal("MigrateUserAssignment must refuse canonical sso: principal as source")
}
})
t.Run("copy fallback", func(t *testing.T) {
manager := &ssoIdentityRBACManager{
assignments: map[string]auth.UserRoleAssignment{
victim: {Username: victim, RoleIDs: []string{auth.RoleAdmin}},
},
}
if err := applySSORoleAssignments(manager, principal, candidates, nil, false, true); err != nil {
t.Fatalf("applySSORoleAssignments: %v", err)
}
if manager.updatedUser != principal || len(manager.updatedRoles) != 0 {
t.Fatalf("caller roles = %q %v, want listed without roles", manager.updatedUser, manager.updatedRoles)
}
})
}
func TestApplySSORoleAssignmentsReplacesStaleRolesWhenMappingNamesMissingRole(t *testing.T) {
for _, tc := range []struct {
name string
mapped []string
want string
}{
{name: "only a missing role", mapped: []string{"deleted-role"}, want: ""},
{name: "missing role beside an existing one", mapped: []string{"deleted-role", auth.RoleViewer}, want: auth.RoleViewer},
} {
t.Run(tc.name, func(t *testing.T) {
manager, err := auth.NewSQLiteManager(auth.SQLiteManagerConfig{DataDir: t.TempDir()})
if err != nil {
t.Fatalf("NewSQLiteManager: %v", err)
}
defer manager.Close()
principal := "sso:oidc:okta:stable"
if err := manager.UpdateUserRoles(principal, []string{auth.RoleAdmin}); err != nil {
t.Fatalf("seed earlier sign-in: %v", err)
}
err = applySSORoleAssignments(manager, principal, nil, tc.mapped, true, true)
if err == nil || errors.Is(err, errSSORolesNotReplaced) {
t.Fatalf("applySSORoleAssignments error = %v, want the recoverable store error", err)
}
assignment, ok := manager.GetUserAssignment(principal)
if got := strings.Join(assignment.RoleIDs, ","); !ok || got != tc.want {
t.Fatalf("roles after a mapping with a missing role = %q, exists=%v, want %q", got, ok, tc.want)
}
})
}
}
type ssoFailingRBACManager struct {
auth.Manager
}
func (ssoFailingRBACManager) UpdateUserRoles(string, []string) error {
return errors.New("store unavailable")
}
func TestApplySSORoleAssignmentsReportsUnreplacedRoles(t *testing.T) {
err := applySSORoleAssignments(ssoFailingRBACManager{}, "sso:saml:okta:stable", nil, nil, true, false)
if !errors.Is(err, errSSORolesNotReplaced) {
t.Fatalf("applySSORoleAssignments error = %v, want errSSORolesNotReplaced", err)
}
}
+14
View File
@@ -362,6 +362,20 @@ func (c *DefaultAuthorizationChecker) CheckAccessContext(ctx context.Context, to
Reason: "Token is not authorized for this organization",
}
}
// A token that acts for its owner (apiTokenActsForOwner) reaches a
// tenant organization only while the owner could: removing a member
// revokes none of their tokens, so the binding alone would outlive
// the membership. Machine credentials stay with the organization
// they were issued for, and default-organization tokens keep the
// binding rule. A checker built without an organization loader has
// no membership data and rechecks bindings only.
if orgID != "default" && c.orgLoader != nil && apiTokenActsForOwner(token) &&
!c.UserCanAccessOrg(apiTokenBoundUser(token), orgID) {
return AuthorizationResult{
Allowed: false,
Reason: "Token owner is not a member of the organization",
}
}
return AuthorizationResult{
Allowed: true,
Reason: "Token authorized for organization",
@@ -0,0 +1,123 @@
package api
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
func orgBoundOwnedToken(owner, orgID string, scopes ...string) *config.APITokenRecord {
record := &config.APITokenRecord{ID: "token", OrgID: orgID, Scopes: scopes}
setAPITokenOwnerUserID(record, owner)
return record
}
// A token that acts for its owner (Pulse Mobile, Assistant, actions, full
// access) must not outlive the owner's membership of the organization it is
// bound to. Machine and plain monitoring credentials follow the binding only.
func TestCheckAccessRequiresMembershipOfTokenOwner(t *testing.T) {
checker := NewAuthorizationChecker(staticOrgLoader{org: &models.Organization{
ID: "acme",
OwnerUserID: "alice",
Members: []models.OrganizationMember{
{UserID: "alice", Role: models.OrgRoleOwner},
{UserID: "carol", Role: models.OrgRoleViewer},
},
}})
bindingOnly := NewAuthorizationChecker(nil)
for _, tc := range []struct {
name string
checker *DefaultAuthorizationChecker
token *config.APITokenRecord
orgID string
allowed bool
}{
{"mobile token of the owner", checker, orgBoundOwnedToken("alice", "acme", config.ScopeRelayMobileAccess), "acme", true},
{"mobile token of a member", checker, orgBoundOwnedToken("carol", "acme", config.ScopeRelayMobileAccess), "acme", true},
{"mobile token of a removed member", checker, orgBoundOwnedToken("bob", "acme", config.ScopeRelayMobileAccess), "acme", false},
{"assistant token of a removed member", checker, orgBoundOwnedToken("bob", "acme", config.ScopeAIChat), "acme", false},
{"action token of a removed member", checker, orgBoundOwnedToken("bob", "acme", config.ScopeMonitoringRead, config.ScopeActionsApprove), "acme", false},
{"full-access token of a removed member", checker, orgBoundOwnedToken("bob", "acme", config.ScopeWildcard), "acme", false},
{"agent token issued by a removed member", checker, orgBoundOwnedToken("bob", "acme", config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeAgentExec), "acme", true},
{"monitoring token issued by a removed member", checker, orgBoundOwnedToken("bob", "acme", config.ScopeMonitoringRead), "acme", true},
{"ownerless token", checker, orgBoundOwnedToken("", "acme", config.ScopeRelayMobileAccess), "acme", true},
{"binding still decides first", checker, orgBoundOwnedToken("alice", "other", config.ScopeRelayMobileAccess), "acme", false},
{"default organization keeps the binding rule", checker, orgBoundOwnedToken("bob", "default", config.ScopeRelayMobileAccess), "default", true},
{"checker without membership data rechecks the binding", bindingOnly, orgBoundOwnedToken("bob", "acme", config.ScopeRelayMobileAccess), "acme", true},
} {
t.Run(tc.name, func(t *testing.T) {
result := tc.checker.CheckAccess(tc.token, apiTokenAuthenticatedUser(tc.token), tc.orgID)
if result.Allowed != tc.allowed {
t.Fatalf("allowed = %v (%s), want %v", result.Allowed, result.Reason, tc.allowed)
}
})
}
result := checker.CheckAccess(orgBoundOwnedToken("bob", "acme", config.ScopeRelayMobileAccess), "bob", "acme")
if result.Reason != "Token owner is not a member of the organization" {
t.Fatalf("reason = %q", result.Reason)
}
}
// Approving and executing a governed action recheck the same policy, so the
// owner of a relay-mobile token must still belong to the organization.
func TestActionAuthorityRequiresMembershipOfTokenOwner(t *testing.T) {
authority := actionAuthority{
authorizer: allowActionAuthorityAuthorizer{},
orgChecker: NewAuthorizationChecker(staticOrgLoader{org: &models.Organization{
ID: "acme",
Members: []models.OrganizationMember{{UserID: "alice", Role: models.OrgRoleAdmin}},
}}),
}
for owner, want := range map[string]error{"alice": nil, "bob": actionlifecycle.ErrActionAuthorizationDenied} {
record := orgBoundOwnedToken(owner, "acme", config.ScopeRelayMobileAccess)
actor := unified.ActionActor{SubjectID: owner, Kind: unified.ActionActorAPIToken, CredentialID: "api-token:" + record.ID, OrgID: "acme"}
for _, capability := range []string{auth.ActionApprove, auth.ActionExecute} {
if err := authority.authorizeActor(actionAuthorityContext(record), "acme", actor, capability); !errors.Is(err, want) {
t.Fatalf("%s %s = %v, want %v", owner, capability, err, want)
}
}
}
}
// A stream admitted for such a token ends when its owner is removed, as a
// signed-in user's stream does.
func TestTokenStreamRevalidationFollowsOwnerMembership(t *testing.T) {
const raw = "synthetic-mobile-token-123.12345678"
record := newTokenRecord(t, raw, []string{config.ScopeRelayMobileAccess}, nil)
record.OrgID = "acme"
setAPITokenOwnerUserID(&record, "bob")
cfg := newTestConfigWithTokens(t, record)
loader := &staticOrgLoader{org: &models.Organization{
ID: "acme",
Members: []models.OrganizationMember{{UserID: "bob", Role: models.OrgRoleAdmin}},
}}
req := httptest.NewRequest(http.MethodGet, "/api/ai/chat", nil)
req.Header.Set("X-API-Token", raw)
attachAPITokenRecord(req, &record)
ctx := context.WithValue(req.Context(), OrgIDContextKey, "acme")
req = req.WithContext(withOrgAccessChecker(ctx, NewAuthorizationChecker(loader)))
revalidate := tokenStreamSnapshotRevalidator(cfg, req, config.ScopeRelayMobileAccess)
if revalidate == nil {
t.Fatal("token request has no revalidator")
}
if _, ok := revalidate(); !ok {
t.Fatal("member's token stream was not admitted")
}
loader.org = &models.Organization{ID: "acme"}
if _, ok := revalidate(); ok {
t.Fatal("token stream outlived its owner's membership")
}
}
@@ -1,6 +1,7 @@
package api
import (
"crypto/ed25519"
"encoding/base64"
"encoding/json"
"net/http"
@@ -14,6 +15,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/license/entitlements"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
)
func TestBillingStateGetReturnsDefaultWhenMissing(t *testing.T) {
@@ -240,6 +242,92 @@ func TestBillingStateGetHostedNonDefaultPrefersOrgBillingStateOverDefaultFallbac
}
}
func TestBillingStateGetOmitsEntitlementCredentials(t *testing.T) {
router, baseDir := newBillingStateTestRouter(t, true)
store := config.NewFileBillingStore(baseDir)
lease := saveLeasedBillingStateForTest(t, store, "default")
// "default" reads its own record; "t-tenant" has none and inherits it.
for _, orgID := range []string{"default", "t-tenant"} {
rec := doBillingStateRequest(router, http.MethodGet, "/api/admin/orgs/"+orgID+"/billing-state", "")
if rec.Code != http.StatusOK {
t.Fatalf("%s: expected 200, got %d: %s", orgID, rec.Code, rec.Body.String())
}
body := rec.Body.String()
if strings.Contains(body, lease) || strings.Contains(body, "etr_hosted_default") ||
strings.Contains(body, "entitlement_jwt") || strings.Contains(body, "entitlement_refresh_token") {
t.Fatalf("%s: billing state response must not carry entitlement credentials, got %s", orgID, body)
}
var payload entitlements.BillingState
if err := decodeResponse(rec, &payload); err != nil {
t.Fatalf("%s: decode response: %v", orgID, err)
}
if payload.SubscriptionState != entitlements.SubStateActive || payload.PlanVersion != "msp_starter" {
t.Fatalf("%s: expected the leased plan to remain visible, got %+v", orgID, payload)
}
}
}
func TestBillingStatePutKeepsStoredEntitlementCredentialsWhenOmitted(t *testing.T) {
router, baseDir := newBillingStateTestRouter(t, true)
store := config.NewFileBillingStore(baseDir)
lease := saveLeasedBillingStateForTest(t, store, "acme")
logs := captureTestLogs(t)
// Write back what a read returns, as the billing admin panel does.
getRec := doBillingStateRequest(router, http.MethodGet, "/api/admin/orgs/acme/billing-state", "")
if getRec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", getRec.Code, getRec.Body.String())
}
putRec := doBillingStateRequest(router, http.MethodPut, "/api/admin/orgs/acme/billing-state", getRec.Body.String())
if putRec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", putRec.Code, putRec.Body.String())
}
if body := putRec.Body.String(); strings.Contains(body, lease) || strings.Contains(body, "etr_hosted_default") {
t.Fatalf("billing state response must not carry entitlement credentials, got %s", body)
}
if logged := logs.String(); !strings.Contains(logged, "Billing state updated") ||
strings.Contains(logged, lease) || strings.Contains(logged, "etr_hosted_default") {
t.Fatalf("billing state audit log must not carry entitlement credentials, got %s", logged)
}
stored, err := store.GetBillingState("acme")
if err != nil {
t.Fatalf("load stored billing state: %v", err)
}
if stored.EntitlementJWT != lease || stored.EntitlementRefreshToken != "etr_hosted_default" {
t.Fatalf("expected stored entitlement credentials to survive the write, got jwt=%q refresh=%q", stored.EntitlementJWT, stored.EntitlementRefreshToken)
}
}
func saveLeasedBillingStateForTest(t *testing.T, store *config.FileBillingStore, orgID string) string {
t.Helper()
pub, priv, err := ed25519.GenerateKey(nil)
if err != nil {
t.Fatalf("GenerateKey: %v", err)
}
t.Setenv(pkglicensing.TrialActivationPublicKeyEnvVar, base64.StdEncoding.EncodeToString(pub))
lease, err := pkglicensing.SignEntitlementLeaseToken(priv, pkglicensing.EntitlementLeaseClaims{
OrgID: orgID,
InstanceHost: "pulse.example.com",
PlanVersion: "msp_starter",
SubscriptionState: pkglicensing.SubStateActive,
Capabilities: []string{pkglicensing.FeatureRelay},
})
if err != nil {
t.Fatalf("SignEntitlementLeaseToken: %v", err)
}
if err := store.SaveBillingState(orgID, &entitlements.BillingState{
EntitlementJWT: lease,
EntitlementRefreshToken: "etr_hosted_default",
}); err != nil {
t.Fatalf("save leased billing state: %v", err)
}
return lease
}
func TestBillingStatePutRejectsInvalidSubscriptionState(t *testing.T) {
router, _ := newBillingStateTestRouter(t, true)
@@ -90,6 +90,87 @@ func TestChangePasswordBasicAuthPathUnaffected(t *testing.T) {
}
}
func newChangePasswordRouterWithToken(t *testing.T, rawToken string, scopes []string) (*Router, *config.Config) {
t.Helper()
dir := t.TempDir()
hashed, err := bcrypt.GenerateFromPassword([]byte(changePasswordProbeCurrent), bcrypt.DefaultCost)
if err != nil {
t.Fatalf("bcrypt: %v", err)
}
record, err := config.NewAPITokenRecord(rawToken, "change-password-caller", scopes)
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
cfg := &config.Config{
DataPath: dir, ConfigPath: dir,
AuthUser: "admin", AuthPass: string(hashed),
APITokens: []config.APITokenRecord{*record},
}
cfg.SortAPITokens()
router := newTestRouter(t, cfg, nil, nil, nil, nil, "1.0.0")
cleanupTestRouter(t, router)
return router, cfg
}
// ensureAdminSession judges sessions and leaves a token's scope to the route,
// and this route asked for none: the report token of one monitored host could
// submit guesses at the admin password and replace it on a hit.
func TestChangePasswordRefusesTokenWithoutSettingsWrite(t *testing.T) {
const rawToken = "change-password-agent-token.12345678"
router, cfg := newChangePasswordRouterWithToken(t, rawToken, []string{config.ScopeAgentReport, config.ScopeAgentConfigRead})
before := cfg.AuthPass
for _, current := range []string{"wrong-guess", changePasswordProbeCurrent} {
req := changePasswordRequest(t, current)
req.Header.Set("X-API-Token", rawToken)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("agent token change-password (%q) = %d, want 403 (body %s)", current, rec.Code, rec.Body.String())
}
}
if cfg.AuthPass != before {
t.Fatal("agent token changed the admin password")
}
}
// Sign-in counts failures per account as well as per address. Password change
// tests the same password, so guesses spread over addresses must meet the same
// account lockout rather than five fresh attempts per address.
func TestChangePasswordCountsFailuresAgainstTheAccount(t *testing.T) {
resetFailedLogins()
t.Cleanup(resetFailedLogins)
const rawToken = "change-password-settings-token.12345678"
router, cfg := newChangePasswordRouterWithToken(t, rawToken, []string{config.ScopeSettingsWrite})
before := cfg.AuthPass
guessFrom := func(address, current string) *httptest.ResponseRecorder {
req := changePasswordRequest(t, current)
req.RemoteAddr = address + ":54321"
req.Header.Set("X-API-Token", rawToken)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
return rec
}
for i := 0; i < maxFailedAttempts; i++ {
if rec := guessFrom("203.0.113."+strconv.Itoa(10+i), "wrong-guess"); rec.Code != http.StatusUnauthorized {
t.Fatalf("wrong guess %d = %d, want 401 (body %s)", i+1, rec.Code, rec.Body.String())
}
}
if _, _, locked := GetLockoutInfo(cfg.AuthUser); !locked {
t.Fatalf("%d wrong current passwords from different addresses did not lock the account", maxFailedAttempts)
}
if rec := guessFrom("203.0.113.200", changePasswordProbeCurrent); rec.Code != http.StatusForbidden {
t.Fatalf("change-password on a locked account = %d, want 403 (body %s)", rec.Code, rec.Body.String())
}
if cfg.AuthPass != before {
t.Fatal("password changed while the account was locked")
}
}
func TestChangePasswordFixtureOwnsRouterLifecycle(t *testing.T) {
var router *Router
workerDone := make(chan struct{})
+1 -1
View File
@@ -116,7 +116,7 @@ func (r *Router) handleHostedTenantAgentInstallCommand(w http.ResponseWriter, re
var payload struct {
Type string `json:"type"` // "pve" or "pbs"
}
if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, req.Body, 4096)).Decode(&payload); err != nil {
writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", map[string]string{"error": err.Error()})
return
}
+13
View File
@@ -26,6 +26,13 @@ const (
cloudHandoffIssuer = "pulse-cloud-control-plane"
handoffPrivateDirPerm = 0o700
handoffPrivateFilePerm = 0o600
// jwt.ParseWithClaims JSON-decodes the token header and claims before it
// checks the signature, so on a public route the sender decides how much
// memory that costs. A control-plane handoff token is a few hundred bytes
// plus its target path.
maxHandoffTokenBytes = 8 * 1024
maxHandoffExchangeRequestBytes = 2 * maxHandoffTokenBytes
)
var errHandoffAuthorizationDenied = errors.New("handoff authorization denied")
@@ -335,6 +342,7 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxHandoffExchangeRequestBytes)
if err := r.ParseForm(); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
@@ -344,6 +352,11 @@ func HandleHandoffExchange(configDir string) http.HandlerFunc {
http.Error(w, "missing token", http.StatusBadRequest)
return
}
// FormValue also reads the query string, which the body limit does not cover.
if len(tokenStr) > maxHandoffTokenBytes {
http.Error(w, "invalid token", http.StatusUnauthorized)
return
}
var claims cloudHandoffClaims
parsed, err := jwt.ParseWithClaims(
@@ -967,3 +967,74 @@ func TestHandleHandoffExchangeKeyMissing(t *testing.T) {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusNotFound)
}
}
// The JWT parser decodes a token's header and claims before it checks the
// signature, so the exchange must refuse an oversized token without parsing
// it, wherever the token arrives. A correctly signed one shows it is the size
// that is refused.
func TestHandleHandoffExchangeBoundsTokenBeforeParsing(t *testing.T) {
key := []byte("test-handoff-key")
configDir := t.TempDir()
resetSessionStoreForTests()
t.Cleanup(resetSessionStoreForTests)
resetCSRFStoreForTests()
t.Cleanup(resetCSRFStoreForTests)
InitSessionStore(configDir)
InitCSRFStore(configDir)
secretsDir := filepath.Join(configDir, "secrets")
if err := os.MkdirAll(secretsDir, 0o755); err != nil {
t.Fatalf("MkdirAll() error = %v", err)
}
if err := os.WriteFile(filepath.Join(secretsDir, "handoff.key"), key, 0o600); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
handler := HandleHandoffExchange(configDir)
tenantID := "tenant-bounded"
host := tenantID + ".example.com"
saveHandoffTestOrganization(t, configDir, &models.Organization{
ID: tenantID,
OwnerUserID: "bounded@example.com",
})
sign := func(targetPath string) string {
return signHandoffToken(t, key, cloudHandoffClaims{
AccountID: "acct-bounded",
Email: "bounded@example.com",
Role: "owner",
TargetPath: targetPath,
RegisteredClaims: jwt.RegisteredClaims{
ID: "jti-bounded",
Subject: "user-bounded",
Issuer: cloudHandoffIssuer,
Audience: jwt.ClaimStrings{tenantID},
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
},
})
}
exchange := func(target, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Host = host
req.RemoteAddr = "127.0.0.1:12345"
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec
}
oversized := sign("/" + strings.Repeat("a", maxHandoffTokenBytes))
if rec := exchange("/api/cloud/handoff/exchange?format=json", "token="+oversized); rec.Code != http.StatusUnauthorized {
t.Fatalf("oversized token in body: status = %d, want %d", rec.Code, http.StatusUnauthorized)
}
if rec := exchange("/api/cloud/handoff/exchange?format=json&token="+oversized, ""); rec.Code != http.StatusUnauthorized {
t.Fatalf("oversized token in query: status = %d, want %d", rec.Code, http.StatusUnauthorized)
}
padded := "token=" + sign("/") + "&pad=" + strings.Repeat("a", maxHandoffExchangeRequestBytes)
if rec := exchange("/api/cloud/handoff/exchange?format=json", padded); rec.Code != http.StatusBadRequest {
t.Fatalf("oversized request body: status = %d, want %d", rec.Code, http.StatusBadRequest)
}
// None of the refusals read the token: its jti is still unspent.
if rec := makeExchangeRequest(t, handler, host, sign("/")); rec.Code != http.StatusOK {
t.Fatalf("ordinary token: status = %d, want %d (body=%q)", rec.Code, http.StatusOK, rec.Body.String())
}
}
+5 -5
View File
@@ -172,7 +172,7 @@ func (h *ConfigProfileHandler) CreateProfile(w http.ResponseWriter, r *http.Requ
models.AgentProfile
ChangeNote string `json:"change_note,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&input); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -281,7 +281,7 @@ func (h *ConfigProfileHandler) UpdateProfile(w http.ResponseWriter, r *http.Requ
models.AgentProfile
ChangeNote string `json:"change_note,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&input); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -484,7 +484,7 @@ func (h *ConfigProfileHandler) ListAssignments(w http.ResponseWriter, r *http.Re
// AssignProfile assigns a profile to an agent
func (h *ConfigProfileHandler) AssignProfile(w http.ResponseWriter, r *http.Request) {
var input models.AgentProfileAssignment
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64*1024)).Decode(&input); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -691,7 +691,7 @@ func (h *ConfigProfileHandler) GetConfigSchema(w http.ResponseWriter, r *http.Re
// ValidateConfig validates a configuration without saving
func (h *ConfigProfileHandler) ValidateConfig(w http.ResponseWriter, r *http.Request) {
var config models.AgentConfigMap
if err := json.NewDecoder(r.Body).Decode(&config); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&config); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
@@ -783,7 +783,7 @@ func (h *ConfigProfileHandler) GetDeploymentStatus(w http.ResponseWriter, r *htt
// UpdateDeploymentStatus updates deployment status from an agent
func (h *ConfigProfileHandler) UpdateDeploymentStatus(w http.ResponseWriter, r *http.Request) {
var input models.ProfileDeploymentStatus
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64*1024)).Decode(&input); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
+28 -2
View File
@@ -123,6 +123,9 @@ func (r *Router) authorizeConfigTransfer(w http.ResponseWriter, req *http.Reques
if op == configTransferImport && !tokenHasInstanceWideAuthority(record) {
keepImportAccessCredentials(req)
}
// Neither credential here passes through CheckAuth; an import archive
// must not arrive after the token or session that admitted it is gone.
retainRequestBodyAuthority(r.config, req)
return true
}
@@ -162,6 +165,7 @@ func (r *Router) authorizeConfigTransfer(w http.ResponseWriter, req *http.Reques
if op == configTransferImport && !sessionUserCarriesAdminPrivileges(r.config, sessionUser) {
keepImportAccessCredentials(req)
}
retainRequestBodyAuthority(r.config, req)
return true
}
}
@@ -177,9 +181,31 @@ func (r *Router) authorizeConfigTransfer(w http.ResponseWriter, req *http.Reques
configuredUser := r.config.AuthUser
configuredHash := r.config.AuthPass
config.Mu.RUnlock()
if configuredUser != "" && configuredHash != "" &&
// This route does not pass through CheckAuth, so the password test
// below keeps sign-in's lockout itself: it refuses while the account
// or the address is locked and atomically counts outcomes against both.
passwordConfigured := configuredUser != "" && configuredHash != ""
clientIP := GetClientIP(req)
if passwordConfigured {
_, _, userLocked := GetLockoutInfo(username)
_, _, ipLocked := GetLockoutInfo(clientIP)
if userLocked || ipLocked {
logAuthDenial(req, username, "Basic credentials refused for configuration transfer during lockout", nil)
http.Error(w, "Too many failed attempts. Please try again later.", http.StatusForbidden)
return false
}
}
credentialsValid := passwordConfigured &&
constantTimeStringEqual(username, configuredUser) &&
internalauth.CheckPasswordHash(password, configuredHash) {
internalauth.CheckPasswordHash(password, configuredHash)
if passwordConfigured {
if _, locked := RecordLoginAttempt(credentialsValid, username, clientIP); locked {
logAuthDenial(req, username, "Basic credentials refused for configuration transfer during lockout", nil)
http.Error(w, "Too many failed attempts. Please try again later.", http.StatusForbidden)
return false
}
}
if credentialsValid {
if access := authorizeVerifiedUserForRequestOrganization(req, configuredUser); !access.Allowed {
logAuthDenial(req, configuredUser, "Basic credentials refused for the request organization during configuration transfer", nil)
writeJSONError(w, http.StatusForbidden, "access_denied", access.Reason)
@@ -288,6 +288,60 @@ func TestConfigTransferAuthorizedInstanceModesReachHandler(t *testing.T) {
})
}
// Export and import test the administrator password outside CheckAuth. They
// must share sign-in's lockout, or they answer password guesses without limit
// to a caller with no credential at all.
func TestConfigTransferBasicPasswordGuessesMeetSignInLockout(t *testing.T) {
const password = "SyntheticPassword!1"
hash, err := internalauth.HashPassword(password)
if err != nil {
t.Fatalf("hash password: %v", err)
}
dataDir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dataDir)
cfg := &config.Config{DataPath: dataDir, ConfigPath: dataDir, AuthUser: "admin", AuthPass: hash}
router := newTestRouter(t, cfg, nil, nil, nil, nil, "test")
cleanupTestRouter(t, router)
resetFailedLogins()
t.Cleanup(resetFailedLogins)
attempt := func(path, address, guess string) (int, int) {
body := &countingConfigTransferBody{reader: strings.NewReader(`{not-json`)}
req := httptest.NewRequest(http.MethodPost, path, body)
req.RemoteAddr = address + ":54321"
req.SetBasicAuth("admin", guess)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
return rec.Code, body.reads
}
for i := 0; i < maxFailedAttempts; i++ {
path := []string{"/api/config/export", "/api/config/import"}[i%2]
if code, reads := attempt(path, "203.0.113."+strconv.Itoa(10+i), "wrong-guess"); code != http.StatusUnauthorized || reads != 0 {
t.Fatalf("wrong guess %d on %s = status %d, reads %d, want 401 before any read", i+1, path, code, reads)
}
}
if _, _, locked := GetLockoutInfo("admin"); !locked {
t.Fatalf("%d wrong passwords from different addresses did not lock the account", maxFailedAttempts)
}
for _, path := range []string{"/api/config/export", "/api/config/import"} {
if code, reads := attempt(path, "203.0.113.200", password); code != http.StatusForbidden || reads != 0 {
t.Errorf("%s on a locked account = status %d, reads %d, want 403 before any read", path, code, reads)
}
}
resetFailedLogins()
if code, _ := attempt("/api/config/export", "203.0.113.201", "wrong-guess"); code != http.StatusUnauthorized {
t.Fatalf("wrong guess = %d, want 401", code)
}
if code, reads := attempt("/api/config/export", "203.0.113.201", password); code != http.StatusBadRequest || reads == 0 {
t.Fatalf("right password after one wrong guess = status %d, reads %d, want the handler's 400", code, reads)
}
if attempts, _, _ := GetLockoutInfo("admin"); attempts != 0 {
t.Fatalf("successful Basic authentication left %d failed attempts on the account", attempts)
}
}
func TestConfigTransferTokenScopesAndOrganizationBinding(t *testing.T) {
readRaw := "synthetic-read-token-123.12345678"
writeRaw := "synthetic-write-token-123.12345678"
@@ -766,8 +820,9 @@ func (b *endSessionOnRead) Read(p []byte) (int, error) {
// that organization and acting for another member. The organization's owner
// manages its settings and may import them, but may not issue its tokens
// (POST /api/security/tokens is instance administration), so the import must
// not issue the archive's either, also when the owner's session ends before
// the archive is read. An instance administrator who also manages the
// not issue the archive's either. When the owner's session ends before the
// archive is read, request-body authority refuses the import with 401 and
// restores nothing. An instance administrator who also manages the
// organization restores them as before.
func TestConfigImportOrganizationManagerKeepsAccessCredentials(t *testing.T) {
f := newBasicTenantFixture(t)
@@ -812,7 +867,7 @@ func TestConfigImportOrganizationManagerKeepsAccessCredentials(t *testing.T) {
}
return tokens, ssoProviders
}
importAs := func(user, remoteAddr string, signOutBeforeRead bool) map[string]any {
importAs := func(user, remoteAddr string, signOutBeforeRead bool) *httptest.ResponseRecorder {
t.Helper()
data, err := source.ExportConfig(passphrase)
if err != nil {
@@ -835,6 +890,11 @@ func TestConfigImportOrganizationManagerKeepsAccessCredentials(t *testing.T) {
req.Header.Set("X-CSRF-Token", generateCSRFToken(sessionToken))
rec := httptest.NewRecorder()
f.router.Handler().ServeHTTP(rec, req)
return rec
}
decodeImport := func(user string, rec *httptest.ResponseRecorder) map[string]any {
t.Helper()
if rec.Code != http.StatusOK {
t.Fatalf("import as %s status = %d: %s", user, rec.Code, rec.Body.String())
}
@@ -845,17 +905,24 @@ func TestConfigImportOrganizationManagerKeepsAccessCredentials(t *testing.T) {
return response
}
for i, signOutBeforeRead := range []bool{false, true} {
response := importAs("managed-owner", "127.0.3."+strconv.Itoa(i+1)+":1234", signOutBeforeRead)
if response["accessCredentialsRestored"] != false {
t.Fatalf("organization owner import (signed out before read: %v) response = %v, want accessCredentialsRestored=false", signOutBeforeRead, response)
}
if tokens, ssoProviders := restored(); tokens != 0 || ssoProviders != 0 {
t.Fatalf("organization owner import (signed out before read: %v) issued %d archived tokens and %d SSO providers", signOutBeforeRead, tokens, ssoProviders)
}
rec := importAs("managed-owner", "127.0.3.1:1234", false)
response := decodeImport("managed-owner", rec)
if response["accessCredentialsRestored"] != false {
t.Fatalf("organization owner import response = %v, want accessCredentialsRestored=false", response)
}
if tokens, ssoProviders := restored(); tokens != 0 || ssoProviders != 0 {
t.Fatalf("organization owner import issued %d archived tokens and %d SSO providers", tokens, ssoProviders)
}
response := importAs(basicTenantAdmin, "127.0.3.3:1234", false)
signedOutRec := importAs("managed-owner", "127.0.3.2:1234", true)
if signedOutRec.Code != http.StatusUnauthorized || signedOutRec.Body.String() != "Authentication required\n" {
t.Fatalf("organization owner import after sign-out status = %d body=%q, want 401 Authentication required", signedOutRec.Code, signedOutRec.Body.String())
}
if tokens, ssoProviders := restored(); tokens != 0 || ssoProviders != 0 {
t.Fatalf("organization owner import after sign-out issued %d archived tokens and %d SSO providers", tokens, ssoProviders)
}
response = decodeImport(basicTenantAdmin, importAs(basicTenantAdmin, "127.0.3.3:1234", false))
if response["accessCredentialsRestored"] != true {
t.Fatalf("instance administrator import response = %v, want accessCredentialsRestored=true", response)
}
@@ -278,6 +278,31 @@ func TestAgentTokenAutoRegisterRevokedWhileOpenChangesNothing(t *testing.T) {
}
}
// Both routes are public and read the body before the setup token is checked,
// so the body is bounded before it is read.
func TestAutoRegisterRejectsOversizedBody(t *testing.T) {
body := `{"type":"pve","host":"https://pve.example:8006","serverName":"` + strings.Repeat("a", 64*1024) + `"}`
for _, tc := range []struct {
path string
handle func(*ConfigHandlers, http.ResponseWriter, *http.Request)
}{
{"/api/auto-register", (*ConfigHandlers).HandleAutoRegister},
{"/api/auto-unregister", (*ConfigHandlers).HandleAutoUnregister},
} {
t.Run(strings.TrimPrefix(tc.path, "/api/"), func(t *testing.T) {
handler := newTestConfigHandlers(t, &config.Config{DataPath: t.TempDir()})
req := httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
tc.handle(handler, rec, req)
if rec.Code != http.StatusBadRequest || strings.TrimSpace(rec.Body.String()) != "Failed to read request body" {
t.Fatalf("%s status = %d body=%q, want 400 Failed to read request body", tc.path, rec.Code, rec.Body.String())
}
})
}
}
// A malformed body is logged by size only: it may carry a setup token.
func TestAutoRegisterParseFailuresDoNotLogTheBody(t *testing.T) {
const secret = "setup-token-must-not-be-logged-0123456789"
@@ -2154,7 +2154,7 @@ func (h *ConfigHandlers) handleAutoUnregister(w http.ResponseWriter, r *http.Req
}
var req AutoUnregisterRequest
body, err := io.ReadAll(r.Body)
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64*1024))
if err != nil {
log.Error().Err(err).Msg("Failed to read auto-unregister request body")
http.Error(w, "Failed to read request body", http.StatusBadRequest)
@@ -2278,7 +2278,7 @@ func (h *ConfigHandlers) handleAutoRegister(w http.ResponseWriter, r *http.Reque
// Parse request body first so the setup token can be validated early.
var req AutoRegisterRequest
body, err := io.ReadAll(r.Body)
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64*1024))
if err != nil {
log.Error().Err(err).Msg("Failed to read request body")
http.Error(w, "Failed to read request body", http.StatusBadRequest)
@@ -3193,7 +3193,7 @@ func (h *ConfigHandlers) handleAgentInstallCommand(w http.ResponseWriter, r *htt
}
var req AgentInstallCommandRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8*1024)).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
+1 -1
View File
@@ -41,7 +41,7 @@ func buildAggregatorInputsWithRuntimeSources(
if monitor != nil && monitor.GetConfig() == cfg {
inputs.apiTokens = monitor.APITokenSnapshot()
} else {
inputs.apiTokens = append([]config.APITokenRecord(nil), cfg.APITokens...)
inputs.apiTokens = snapshotAPITokenRecords(cfg)
}
inputs.agentTokenInventoryKnown = true
inputs.pvePollingInterval = cfg.PVEPollingInterval
+32 -17
View File
@@ -7371,7 +7371,7 @@ func TestContract_OnboardingDeepLinkIgnoresQueryAuthToken(t *testing.T) {
}
}
func TestContract_SetupTokenRoutesRejectQueryAuthToken(t *testing.T) {
func TestContract_TemperatureSSHRoutesRejectSetupToken(t *testing.T) {
cfg := newTestConfigWithTokens(t, newTokenRecord(t, "settings-write-token", []string{config.ScopeSettingsWrite}, nil))
router := newTestRouter(t, cfg, nil, nil, nil, nil, "1.0.0")
t.Setenv("HOME", t.TempDir())
@@ -7380,7 +7380,7 @@ func TestContract_SetupTokenRoutesRejectQueryAuthToken(t *testing.T) {
tokenHash := authpkg.HashAPIToken(token)
router.configHandlers.StoreSetupToken(tokenHash, &SetupTokenRecord{ExpiresAt: time.Now().Add(time.Minute)})
t.Run("verify-temperature-ssh requires header token transport", func(t *testing.T) {
t.Run("verify-temperature-ssh rejects setup token in query and header", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/api/system/verify-temperature-ssh?auth_token="+token, strings.NewReader(`{"nodes":""}`))
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
@@ -7394,12 +7394,12 @@ func TestContract_SetupTokenRoutesRejectQueryAuthToken(t *testing.T) {
rec = httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d when setup token is provided in header", rec.Code, http.StatusOK)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want %d when setup token is provided in header", rec.Code, http.StatusUnauthorized)
}
})
t.Run("ssh-config requires header token transport", func(t *testing.T) {
t.Run("ssh-config rejects setup token in query and header", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/api/system/ssh-config?auth_token="+token, strings.NewReader("Host example\nHostname example\n"))
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
@@ -7413,8 +7413,8 @@ func TestContract_SetupTokenRoutesRejectQueryAuthToken(t *testing.T) {
rec = httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d when setup token is provided in header", rec.Code, http.StatusOK)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want %d when setup token is provided in header", rec.Code, http.StatusUnauthorized)
}
})
}
@@ -19002,7 +19002,7 @@ func TestContract_AgentEventsStreamPublishesOnApprovalPending(t *testing.T) {
if !strings.Contains(src, "r.aiHandler.SetApprovalCreatedCallback(") {
t.Error("router.go must install the approval-created callback on AIHandler so the agent SSE stream is wired before the first approval lands")
}
if !strings.Contains(src, "broadcaster.PublishApprovalPending(AgentEventApprovalPendingPayload{") {
if !strings.Contains(src, "broadcaster.PublishApprovalPending(req.OrgID, AgentEventApprovalPendingPayload{") {
t.Error("router.go must bridge approval creation into PublishApprovalPending — drift means agents lose the push-notification path for governance state")
}
if !strings.Contains(src, "ApprovalID: req.ID") {
@@ -19081,7 +19081,7 @@ func TestContract_AgentEventsStreamPublishesOnActionCompleted(t *testing.T) {
if !strings.Contains(src, "executor.SetOnActionCompleted(func(record unifiedresources.ActionAuditRecord)") {
t.Error("router.go must install the post-completion callback on the executor returned from chatService.GetExecutor() so the agent SSE stream is wired per-org")
}
if !strings.Contains(src, "broadcaster.PublishActionCompletedRecord(record)") {
if !strings.Contains(src, "broadcaster.PublishActionCompletedRecord(orgID, record)") {
t.Error("router.go must bridge executor action completion into PublishActionCompletedRecord — drift means agents lose the push-notification path for dispatch outcomes")
}
if !strings.Contains(src, "r.resourceHandlers.SetActionCompletedPublisher(r.agentEventBroadcaster.PublishActionCompletedRecord)") {
@@ -19092,7 +19092,7 @@ func TestContract_AgentEventsStreamPublishesOnActionCompleted(t *testing.T) {
t.Fatalf("read agent_events.go: %v", err)
}
eventsSrc := string(eventsSource)
if !strings.Contains(eventsSrc, "func (b *AgentEventBroadcaster) PublishActionCompletedRecord(record unifiedresources.ActionAuditRecord)") {
if !strings.Contains(eventsSrc, "func (b *AgentEventBroadcaster) PublishActionCompletedRecord(orgID string, record unifiedresources.ActionAuditRecord)") {
t.Error("agent_events.go must keep a shared action-audit-record projector for every action.completed producer")
}
if !strings.Contains(eventsSrc, "ActionID: record.ID") {
@@ -25895,7 +25895,7 @@ func TestContract_ConfigImportIncompleteRuntimeKeepsCommittedOutcome(t *testing.
func TestContractSSOEnvironmentBoundaryConsumer(t *testing.T) {
fixture := environmentBoundaryRouter(t)
const token = "sso-environment-consumer-synthetic-token.12345678"
record := newTokenRecord(t, token, []string{config.ScopeSettingsRead, config.ScopeSettingsWrite}, nil)
record := newTokenRecord(t, token, []string{config.ScopeWildcard}, nil)
cfg := newTestConfigWithTokens(t, record)
cfg.PublicURL = "https://pulse.example.test"
var probe *environmentBoundaryEndpointProbe
@@ -26370,8 +26370,9 @@ func TestContract_PulseMCPReadmeIntroNamesPublishedReadTools(t *testing.T) {
}
// Change events reach only subscribers in the organization whose monitor
// recorded them, and finding events only those in the organization whose
// Patrol raised them.
// recorded them, finding events only those in the organization whose
// Patrol raised them, and approval and action events only those in the
// organization that owns the approval or action.
func TestContract_AgentChangeEventsStayInsideTheirOrganization(t *testing.T) {
b := NewAgentEventBroadcaster()
producer, _ := newTestAgentChangeEventProducer(b)
@@ -26399,6 +26400,14 @@ func TestContract_AgentChangeEventsStayInsideTheirOrganization(t *testing.T) {
producer.observer("tenant-b", nil)(unifiedresources.ResourceChange{ID: "foreign", ResourceID: "vm-b", Kind: unifiedresources.ChangeAlertFired})
producer.observer("", nil)(unifiedresources.ResourceChange{ID: "default-org", ResourceID: "vm-d", Kind: unifiedresources.ChangeAlertFired})
producer.observer("tenant-a", nil)(unifiedresources.ResourceChange{ID: "own", ResourceID: "vm-a", Kind: unifiedresources.ChangeAlertFired})
b.PublishApprovalPending("tenant-b", AgentEventApprovalPendingPayload{ApprovalID: "foreign-approval"})
b.PublishApprovalPending("", AgentEventApprovalPendingPayload{ApprovalID: "default-approval"})
b.PublishApprovalPending("tenant-a", AgentEventApprovalPendingPayload{ApprovalID: "own-approval"})
completed := unifiedresources.ActionAuditRecord{State: unifiedresources.ActionStateCompleted}
for _, action := range [][2]string{{"tenant-b", "foreign-action"}, {"", "default-action"}, {"tenant-a", "own-action"}} {
completed.ID = action[1]
b.PublishActionCompletedRecord(action[0], completed)
}
b.PublishFindingCreated("tenant-b", AgentEventFindingCreatedPayload{FindingID: "foreign-finding"})
b.PublishFindingCreated("", AgentEventFindingCreatedPayload{FindingID: "default-finding"})
b.PublishFindingCreated("tenant-a", AgentEventFindingCreatedPayload{FindingID: "own-finding"})
@@ -26421,7 +26430,13 @@ func TestContract_AgentChangeEventsStayInsideTheirOrganization(t *testing.T) {
if !strings.Contains(stream, "event: alert.fired") || !strings.Contains(stream, `"changeId":"own"`) {
t.Fatalf("own organization's alert missing from stream:\n%s", stream)
}
for _, foreign := range []string{`"changeId":"foreign"`, `"changeId":"default-org"`, "foreign-finding", "default-finding"} {
for _, own := range []string{"own-approval", "own-action"} {
if !strings.Contains(stream, own) {
t.Fatalf("own organization's %s missing from stream:\n%s", own, stream)
}
}
for _, foreign := range []string{`"changeId":"foreign"`, `"changeId":"default-org"`, "foreign-finding", "default-finding",
"foreign-approval", "default-approval", "foreign-action", "default-action"} {
if strings.Contains(stream, foreign) {
t.Fatalf("stream leaked %s:\n%s", foreign, stream)
}
@@ -26449,7 +26464,7 @@ func TestAgentEventTokenLifecycleRefreshesDisclosure(t *testing.T) {
control := openAgentLifecycleStream(t, server, agentEventControlToken, "header")
record := agentDisclosureRecord(t, false)
before, _ := json.Marshal(record)
router.agentEventBroadcaster.PublishActionCompletedRecord(record)
router.agentEventBroadcaster.PublishActionCompletedRecord("default", record)
for _, stream := range []*agentLifecycleStream{primary, control} {
body, _ := json.Marshal(stream.next(t))
assertAgentDisclosureWire(t, body, false)
@@ -26458,8 +26473,8 @@ func TestAgentEventTokenLifecycleRefreshesDisclosure(t *testing.T) {
config.Mu.Lock()
cfg.APITokens[0].Scopes = []string{config.ScopeMonitoringRead}
config.Mu.Unlock()
router.agentEventBroadcaster.PublishApprovalPending(AgentEventApprovalPendingPayload{ApprovalID: "after-downgrade", Command: agentPrivateDetail})
router.agentEventBroadcaster.PublishActionCompletedRecord(record)
router.agentEventBroadcaster.PublishApprovalPending("default", AgentEventApprovalPendingPayload{ApprovalID: "after-downgrade", Command: agentPrivateDetail})
router.agentEventBroadcaster.PublishActionCompletedRecord("default", record)
for i, stream := range []*agentLifecycleStream{primary, control} {
approval, _ := json.Marshal(stream.next(t))
if strings.Contains(string(approval), agentPrivateDetail) != (i == 1) {
@@ -52,7 +52,7 @@ type agentDockerContainerPostconditionObserver struct {
}
func (o agentDockerContainerPostconditionObserver) ObserveDockerContainer(ctx context.Context, actionID, agentID, runtime, containerID string) (dockerContainerPostconditionObservation, error) {
result, err := o.commander.ObserveDockerContainer(ctx, agentID, agentexec.DockerContainerObservationPayload{
result, err := o.commander.ObserveDockerContainer(agentCommandContext(ctx), agentID, agentexec.DockerContainerObservationPayload{
ActionID: actionID, Runtime: runtime, ContainerID: containerID,
})
if err != nil {
@@ -10,6 +10,7 @@ import (
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
@@ -271,6 +272,87 @@ func TestDockerContainerActionExecutorUsesProductionDaemonObservationForIndepend
}
}
// Two organizations can each hold a command session under the same agent ID.
// The post-action daemon observation must be asked of the session in the
// action's own organization, as the mutation it verifies was.
func TestDockerContainerPostconditionObserverAsksTheActionsOwnOrganization(t *testing.T) {
server := agentexec.NewServerWithAdmissionValidator(
func(token, agentID, hostname string) (agentexec.AgentAdmission, bool) {
return agentexec.AgentAdmission{OrganizationID: token, TokenID: token, AgentID: agentID, Hostname: hostname}, true
},
func(agentexec.AgentAdmission) bool { return true },
)
websocketServer := httptest.NewServer(http.HandlerFunc(server.HandleWebSocket))
t.Cleanup(websocketServer.Close)
asked := make(chan string, 2)
connect := func(organizationID, state string) {
t.Helper()
conn, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(websocketServer.URL, "http"), http.Header{"Origin": []string{websocketServer.URL}})
if err != nil {
t.Fatalf("dial agent websocket: %v", err)
}
t.Cleanup(func() { conn.Close() })
register, err := agentexec.NewMessage(agentexec.MsgTypeAgentRegister, "", agentexec.AgentRegisterPayload{
AgentID: "shared-agent-id", Hostname: organizationID + "-host", Token: organizationID,
DockerObservationVersion: agentexec.DockerContainerObservationProtocolVersion,
})
if err != nil {
t.Fatal(err)
}
if err := conn.WriteJSON(register); err != nil {
t.Fatalf("write registration: %v", err)
}
var response agentexec.Message
var registered agentexec.RegisteredPayload
if err := conn.ReadJSON(&response); err != nil {
t.Fatalf("read registration response: %v", err)
}
if err := response.DecodePayload(&registered); err != nil || !registered.Success {
t.Fatalf("registration failed: payload=%+v err=%v", registered, err)
}
go func() {
for {
var message agentexec.Message
if err := conn.ReadJSON(&message); err != nil {
return
}
if message.Type != agentexec.MsgTypeDockerContainerObserve {
continue
}
var req agentexec.DockerContainerObservationPayload
if err := message.DecodePayload(&req); err != nil {
return
}
asked <- organizationID
reply, err := agentexec.NewMessage(agentexec.MsgTypeDockerContainerObserveResult, req.RequestID, agentexec.DockerContainerObservationResultPayload{
RequestID: req.RequestID, ActionID: req.ActionID, ProtocolVersion: req.ProtocolVersion, RequestDigest: req.RequestDigest,
Observed: true,
Snapshot: agentexec.DockerContainerObservationSnapshot{ContainerID: req.ContainerID, State: state, Running: state == "running", Health: agentexec.DockerContainerHealthNone, ObservedAt: time.Now().UTC()},
})
if err != nil || conn.WriteJSON(reply) != nil {
return
}
}
}()
}
connect("default", "running")
connect("acme", "exited")
ctx, cancel := context.WithTimeout(context.WithValue(context.Background(), OrgIDContextKey, "acme"), 5*time.Second)
defer cancel()
observation, err := agentDockerContainerPostconditionObserver{commander: server}.ObserveDockerContainer(ctx, "act_container", "shared-agent-id", "docker", strings.Repeat("a", 64))
if err != nil {
t.Fatalf("ObserveDockerContainer: %v", err)
}
if organizationID := <-asked; organizationID != "acme" || len(asked) != 0 {
t.Fatalf("observation was asked of organization %q (%d more), want only acme", organizationID, len(asked))
}
if observation.Snapshot.State != "exited" || observation.Snapshot.Running {
t.Fatalf("snapshot = %#v, want the acme daemon's answer", observation.Snapshot)
}
}
func TestDockerContainerActionExecutorReachesOwnAgentUnderAcknowledgedID(t *testing.T) {
now := time.Now().UTC()
resource := dockerContainerActionResource("app-container:api", "docker", "running", now)
@@ -106,3 +106,53 @@ func TestSessionUserHasRBACAdminGrant(t *testing.T) {
t.Fatal("unassigned user must not carry the admin grant")
}
}
// The session checkAuth admitted a request with decides the administrator
// checks that follow. When it ended in between (sign-out, expiry, revocation)
// the checks used to find no valid cookie and treat the request as one a
// proxy, Basic or token credential had admitted, which handed a signed-out
// viewer instance administration.
func TestAdminSessionChecksRefuseSessionEndedAfterAdmission(t *testing.T) {
InitSessionStore(t.TempDir())
installTestRBACManager(t)
cfg := &config.Config{AuthUser: "richard", AuthPass: "unused-hash"}
admit := func(t *testing.T, username string) (*http.Request, string) {
t.Helper()
token := generateSessionToken()
GetSessionStore().CreateSession(token, time.Hour, "agent", "127.0.0.1", username)
req := httptest.NewRequest(http.MethodPut, "/api/security/sso/providers/company", nil)
req.AddCookie(&http.Cookie{Name: "pulse_session", Value: token})
if !checkAuth(cfg, httptest.NewRecorder(), req, false) {
t.Fatalf("session for %q was not admitted", username)
}
return req, token
}
checks := map[string]func(*http.Request) bool{
"ensureAdminSession": func(req *http.Request) bool {
return ensureAdminSession(cfg, httptest.NewRecorder(), req)
},
"ensureOrgAdminSession": func(req *http.Request) bool {
return ensureOrgAdminSession(cfg, httptest.NewRecorder(), req)
},
"requestCarriesInstanceAuthority": func(req *http.Request) bool {
return requestCarriesInstanceAuthority(cfg, req)
},
}
for name, check := range checks {
t.Run(name, func(t *testing.T) {
req, _ := admit(t, "richard")
if !check(req) {
t.Fatal("live administrator session was refused")
}
for _, user := range []string{"mallory", "richard"} {
req, token := admit(t, user)
GetSessionStore().DeleteSession(token)
if check(req) {
t.Fatalf("session of %q that ended after admission was admitted", user)
}
}
})
}
}
+158 -1
View File
@@ -12,6 +12,8 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/license/entitlements"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
@@ -145,6 +147,160 @@ func TestHostedSignupHostedModeGate(t *testing.T) {
}
}
// A runtime the control plane provisioned for one workspace is reachable at
// that workspace's public address, and its organization, owner and entitlement
// come from the control plane. Its signup route must stay closed to everyone.
func TestHostedSignupClosedOnProvisionedWorkspaceRuntime(t *testing.T) {
t.Setenv("PULSE_TENANT_ID", "t-workspace")
router, persistence, _, emailer, baseDir := newHostedSignupTestRouter(t, true)
addedAt := time.Unix(1700000000, 0).UTC()
if err := persistence.SaveOrganization(&models.Organization{
ID: "t-workspace",
DisplayName: "Workspace",
CreatedAt: addedAt,
OwnerUserID: "u_workspace_owner",
OwnerEmail: "alice.smith@example.com",
Members: []models.OrganizationMember{
{UserID: "u_workspace_owner", Email: "alice.smith@example.com", Role: models.OrgRoleOwner, AddedAt: addedAt, AddedBy: "u_workspace_owner"},
},
}); err != nil {
t.Fatalf("save workspace org: %v", err)
}
for _, email := range []string{"alice.smith@example.com", "alice.\u017fmith@example.com", "stranger@example.com"} {
rec := doHostedSignupRequest(router, fmt.Sprintf(`{"email":%q,"org_name":"anything"}`, email))
if rec.Code != http.StatusNotFound {
t.Fatalf("signup for %q on a provisioned runtime: expected 404, got %d: %s", email, rec.Code, rec.Body.String())
}
}
org, err := persistence.LoadOrganization("t-workspace")
if err != nil {
t.Fatalf("load workspace org: %v", err)
}
if org.OwnerUserID != "u_workspace_owner" || org.OwnerEmail != "alice.smith@example.com" {
t.Fatalf("workspace owner = (%q, %q), want it unchanged", org.OwnerUserID, org.OwnerEmail)
}
if len(org.Members) != 1 || org.Members[0].UserID != "u_workspace_owner" {
t.Fatalf("workspace members = %+v, want the owner unchanged", org.Members)
}
state, err := config.NewFileBillingStore(baseDir).GetBillingState("t-workspace")
if err != nil {
t.Fatalf("get workspace billing state: %v", err)
}
if state != nil {
t.Fatalf("expected no billing state beside the control plane's, got %+v", state)
}
orgs, err := persistence.ListOrganizations()
if err != nil {
t.Fatalf("list orgs: %v", err)
}
for _, listed := range orgs {
if listed != nil && listed.ID != "default" && listed.ID != "t-workspace" {
t.Fatalf("signup created organization %q inside a provisioned runtime", listed.ID)
}
}
emailer.mu.Lock()
defer emailer.mu.Unlock()
if emailer.calls != 0 {
t.Fatalf("expected no magic link email, got %d", emailer.calls)
}
}
// Signing up again with an owner's address resolves to the organization that
// owner already has. The request must not put it back on a trial.
func TestHostedSignupExistingOwnerKeepsBillingState(t *testing.T) {
router, persistence, _, emailer, baseDir := newHostedSignupTestRouter(t, true)
first := doHostedSignupRequest(router, `{"email":"owner@example.com","org_name":"My Organization"}`)
if first.Code != http.StatusAccepted {
t.Fatalf("first signup expected 202, got %d: %s", first.Code, first.Body.String())
}
orgID := requireHostedSignupProvisionedOrgID(t, persistence, "owner@example.com")
store := config.NewFileBillingStore(baseDir)
seeded, err := store.GetBillingState(orgID)
if err != nil {
t.Fatalf("get seeded billing state: %v", err)
}
if seeded == nil || seeded.SubscriptionState != entitlements.SubStateTrial || seeded.PlanVersion != "cloud_trial" {
t.Fatalf("expected a seeded cloud trial for the new organization, got %+v", seeded)
}
if err := store.SaveBillingState(orgID, &entitlements.BillingState{
Capabilities: seeded.Capabilities,
Limits: map[string]int64{"max_monitored_systems": 10},
PlanVersion: "cloud_starter",
SubscriptionState: entitlements.SubStateActive,
}); err != nil {
t.Fatalf("save active billing state: %v", err)
}
second := doHostedSignupRequest(router, `{"email":"Owner@Example.com","org_name":"Another Name"}`)
if second.Code != http.StatusAccepted {
t.Fatalf("second signup expected 202, got %d: %s", second.Code, second.Body.String())
}
state, err := store.GetBillingState(orgID)
if err != nil {
t.Fatalf("get billing state after second signup: %v", err)
}
if state == nil || state.SubscriptionState != entitlements.SubStateActive || state.PlanVersion != "cloud_starter" {
t.Fatalf("expected the active subscription to survive a repeated signup, got %+v", state)
}
if state.TrialStartedAt != nil || state.TrialEndsAt != nil {
t.Fatalf("expected no trial window on the active subscription, got started=%v ends=%v", state.TrialStartedAt, state.TrialEndsAt)
}
emailer.mu.Lock()
defer emailer.mu.Unlock()
if emailer.calls != 2 {
t.Fatalf("expected a sign-in link for each accepted request, got %d", emailer.calls)
}
}
// Rollback undoes what a failed signup created. An organization that was
// already there is not that request's to delete.
func TestHostedSignupExistingOrganizationSurvivesMagicLinkFailure(t *testing.T) {
router, persistence, rbacProvider, emailer, _ := newHostedSignupTestRouter(t, true)
first := doHostedSignupRequest(router, `{"email":"owner@example.com","org_name":"My Organization"}`)
if first.Code != http.StatusAccepted {
t.Fatalf("first signup expected 202, got %d: %s", first.Code, first.Body.String())
}
orgID := requireHostedSignupProvisionedOrgID(t, persistence, "owner@example.com")
before, err := persistence.LoadOrganization(orgID)
if err != nil {
t.Fatalf("load org: %v", err)
}
emailer.mu.Lock()
emailer.err = fmt.Errorf("forced SendMagicLink failure")
emailer.mu.Unlock()
second := doHostedSignupRequest(router, `{"email":"owner@example.com","org_name":"My Organization"}`)
if second.Code != http.StatusInternalServerError {
t.Fatalf("second signup expected 500, got %d: %s", second.Code, second.Body.String())
}
after, err := persistence.LoadOrganization(orgID)
if err != nil {
t.Fatalf("expected the existing organization to survive a failed repeat signup: %v", err)
}
if after.OwnerUserID != before.OwnerUserID || after.OwnerEmail != before.OwnerEmail || len(after.Members) != len(before.Members) {
t.Fatalf("existing organization changed: before=%+v after=%+v", before, after)
}
manager, err := rbacProvider.GetManager(orgID)
if err != nil {
t.Fatalf("get rbac manager: %v", err)
}
assignment, ok := manager.GetUserAssignment(before.OwnerUserID)
if !ok || !containsRoleID(assignment.RoleIDs, auth.RoleAdmin) {
t.Fatalf("expected the owner to keep the admin role, got %+v (found=%v)", assignment, ok)
}
}
func TestHostedSignupRateLimit(t *testing.T) {
router, _, _, _, _ := newHostedSignupTestRouter(t, true)
@@ -415,6 +571,7 @@ type captureMagicLinkEmailer struct {
calls int
to string
magicLinkURL string
err error
}
func (c *captureMagicLinkEmailer) SendMagicLink(to, magicLinkURL string) error {
@@ -423,5 +580,5 @@ func (c *captureMagicLinkEmailer) SendMagicLink(to, magicLinkURL string) error {
c.calls++
c.to = to
c.magicLinkURL = magicLinkURL
return nil
return c.err
}
+43
View File
@@ -1,6 +1,7 @@
package api
import (
"net/http"
"strconv"
"strings"
"sync"
@@ -66,6 +67,7 @@ func initHTTPMetrics() {
func recordAPIRequest(method, route string, status int, elapsed time.Duration) {
httpMetricsOnce.Do(initHTTPMetrics)
method = metricMethodLabel(method)
statusCode := strconv.Itoa(status)
apiRequestDuration.WithLabelValues(method, route, statusCode).Observe(elapsed.Seconds())
@@ -92,6 +94,47 @@ func classifyStatus(status int) string {
}
}
// unmatchedRouteLabel is the route label of a request that no registered
// pattern serves: unknown API paths and everything the frontend answers.
const unmatchedRouteLabel = "unmatched"
// muxRouteLabel labels a request with the registered pattern that serves it.
// Patterns are a fixed set chosen at startup, so a client that invents paths
// cannot add metric series the way it can with a label built from the path.
func muxRouteLabel(mux *http.ServeMux, r *http.Request) string {
// For CONNECT, ServeMux can report the request's own path as the pattern.
if r.Method == http.MethodConnect {
return unmatchedRouteLabel
}
_, pattern := mux.Handler(r)
// "GET /api/orgs/{id}": the method already has its own label.
if idx := strings.LastIndexByte(pattern, ' '); idx >= 0 {
pattern = pattern[idx+1:]
}
if pattern == "" {
return unmatchedRouteLabel
}
return pattern
}
var metricMethodLabels = [...]string{
http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch,
http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace,
}
// metricMethodLabel maps a request method to one of a fixed set of labels. The
// method is any token the client sends, and net/http hands it over as part of
// the request line: stored as a label, it would be an unbounded value that
// also keeps that whole line, query included, alive.
func metricMethodLabel(method string) string {
for _, label := range metricMethodLabels {
if method == label {
return label
}
}
return "other"
}
func normalizeRoute(path string) string {
if path == "" || path == "/" {
return "/"
+122
View File
@@ -11,6 +11,7 @@ import (
"testing"
"github.com/prometheus/client_golang/prometheus"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
)
// This deliberately keeps the original split/join algorithm and classifiers
@@ -285,6 +286,127 @@ func TestErrorHandler_NormalizedRouteMetrics(t *testing.T) {
}
}
func TestMuxRouteLabel(t *testing.T) {
mux := http.NewServeMux()
for _, pattern := range []string{"/api/state", "/api/agents/", "GET /api/orgs/{id}", "/api/tree/{id}/"} {
mux.HandleFunc(pattern, func(http.ResponseWriter, *http.Request) {})
}
for _, c := range []struct{ method, target, want string }{
{"GET", "/api/state", "/api/state"},
{"HEAD", "/api/state?secret=never/a/label", "/api/state"},
{"GET", "/api/state/made-up", unmatchedRouteLabel},
{"POST", "/api/agents/made-up/config", "/api/agents/"},
{"GET", "/api/orgs/made-up", "/api/orgs/{id}"},
{"DELETE", "/api/orgs/made-up", unmatchedRouteLabel},
{"GET", "/made-up/x", unmatchedRouteLabel},
{"MADEUP", "/made-up/x", unmatchedRouteLabel},
// Redirects to a registered subtree or to the cleaned path.
{"GET", "/api/agents", "/api/agents/"},
{"GET", "/api/tree/made-up", "/api/tree/{id}/"},
{"GET", "/api//state", "/api/state"},
{"GET", "/api//made-up", unmatchedRouteLabel},
// ServeMux names the redirect target, not a pattern, for CONNECT.
{"CONNECT", "/api/tree/made-up", unmatchedRouteLabel},
{"CONNECT", "/api/state", unmatchedRouteLabel},
} {
if got := muxRouteLabel(mux, httptest.NewRequest(c.method, c.target, nil)); got != c.want {
t.Errorf("muxRouteLabel(%s %s) = %q, want %q", c.method, c.target, got, c.want)
}
}
}
func TestMetricMethodLabel(t *testing.T) {
for method, want := range map[string]string{
"GET": "GET", "HEAD": "HEAD", "POST": "POST", "PUT": "PUT", "PATCH": "PATCH", "DELETE": "DELETE",
"CONNECT": "CONNECT", "OPTIONS": "OPTIONS", "TRACE": "TRACE",
"": "other", "get": "other", "MADEUP1": "other", "GET1": "other", "PROPFIND": "other",
} {
if got := metricMethodLabel(method); got != want {
t.Errorf("metricMethodLabel(%q) = %q, want %q", method, got, want)
}
}
}
type httpMetricSeries struct{ method, route string }
// httpRequestTotals sums pulse_http_requests_total over status per method and route.
func httpRequestTotals(t *testing.T) map[httpMetricSeries]float64 {
t.Helper()
registry := prometheus.NewRegistry()
registry.MustRegister(apiRequestTotal)
families, err := registry.Gather()
if err != nil {
t.Fatal(err)
}
totals := make(map[httpMetricSeries]float64)
for _, family := range families {
for _, metric := range family.Metric {
var series httpMetricSeries
for _, label := range metric.Label {
switch label.GetName() {
case "method":
series.method = label.GetValue()
case "route":
series.route = label.GetValue()
}
}
totals[series] += metric.GetCounter().GetValue()
}
}
return totals
}
// Path and method are whatever the client sends, before any authentication.
// Behind the router neither becomes a label value: made-up ones are counted in
// series that a fixed set of labels already allows, whatever the response.
func TestRouter_MadeUpPathsAndMethodsAddNoMetricSeries(t *testing.T) {
httpMetricsOnce.Do(initHTTPMetrics)
router := newTestRouter(t, &config.Config{DataPath: t.TempDir()}, nil, nil, nil, nil, "test")
handler := router.Handler()
serve := func(method, target string) {
handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(method, target, nil))
}
const requests = 64
want := map[httpMetricSeries]float64{
{"HEAD", unmatchedRouteLabel}: requests, // frontend paths
{"GET", unmatchedRouteLabel}: requests, // unknown API paths
{"other", "/api/health"}: requests,
{"other", "/api/agents/agent/"}: requests,
{"GET", "/api/health"}: 1,
{"GET", "/api/agents/agent/"}: 1,
}
before := httpRequestTotals(t)
for i := range requests {
id := strconv.Itoa(i)
serve("HEAD", "/metricroute-madeup"+id+"/x?secret="+id)
serve("GET", "/api/metricroute-madeup"+id)
serve("MADEUP"+id, "/api/health")
serve("MADEUP"+id, "/api/agents/agent/metricroute-madeup"+id+"/config")
}
serve("GET", "/api/health")
serve("GET", "/api/agents/agent/metricroute-madeup/config")
after := httpRequestTotals(t)
madeUp := 0
for series := range after {
if strings.Contains(series.route, "metricroute-madeup") || strings.HasPrefix(series.method, "MADEUP") {
madeUp++
if madeUp == 1 {
t.Errorf("client-chosen path or method became a label: %+v", series)
}
}
}
if madeUp != 0 {
t.Errorf("%d made-up requests created %d series, want 0", 4*requests, madeUp)
}
for series, count := range want {
if delta := after[series] - before[series]; delta < count {
t.Errorf("series %+v counted %v requests, want %v", series, delta, count)
}
}
}
func BenchmarkNormalizeRoute_DiscardedSuffix(b *testing.B) {
for _, count := range []int{8, 2048} {
b.Run(strconv.Itoa(count), func(b *testing.B) {
@@ -60,12 +60,12 @@ func TestContract_HostedIdentityUsesStablePrincipals(t *testing.T) {
"handoff user id must be a stable subject",
},
"oidc_handlers.go": {
"stableSSOPrincipal(config.SSOProviderTypeOIDC, providerID, idToken.Subject)",
"stableSSOPrincipalForIssuer(internalauth.GetManager(), config.SSOProviderTypeOIDC, providerID, verifiedIssuer, idToken.Subject)",
"applySSORoleAssignments(authManager, principal",
"establishOIDCSession(w, req, principal, username, oidcTokens)",
},
"saml_handlers.go": {
"stableSSOPrincipal(config.SSOProviderTypeSAML, providerID, result.NameID)",
"stableSSOPrincipalForIssuer(internalauth.GetManager(), config.SSOProviderTypeSAML, providerID, verifiedIssuer, result.NameID)",
"applySSORoleAssignments(authManager, principal",
"establishSAMLSession(w, req, principal, result.Username, samlSession)",
},
+85
View File
@@ -22,6 +22,7 @@ import (
"github.com/google/uuid"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
"github.com/rs/zerolog/log"
)
@@ -356,6 +357,16 @@ func (r *Router) commitSSOConfig(mutate func(*config.SSOConfig) error) (applyErr
return fmt.Errorf("invalid SAML SP paths for provider %q: %w", provider.ID, err), nil
}
}
// Record the original issuer of every existing provider before an edit or
// deletion can repoint its ID at another IdP. If a provider is deleted or
// its issuer config changes while its original issuer cannot be resolved,
// fail closed so future logins on that ID get issuer-scoped principals.
for i := range current.Providers {
prev := &current.Providers[i]
updated := next.GetProvider(prev.ID)
retargetedOrRemoved := updated == nil || ssoProviderIssuerChanged(prev, updated)
r.bindSSOProviderOriginalIssuer(prev, retargetedOrRemoved)
}
if err := r.persistSSOConfigLocked(next); err != nil {
return nil, err
}
@@ -363,6 +374,80 @@ func (r *Router) commitSSOConfig(mutate func(*config.SSOConfig) error) (applyErr
return nil, nil
}
func ssoProviderIssuerChanged(prev, next *config.SSOProvider) bool {
if prev == nil || next == nil || prev.Type != next.Type {
return true
}
switch prev.Type {
case config.SSOProviderTypeOIDC:
if prev.OIDC == nil || next.OIDC == nil {
return true
}
return strings.TrimSpace(prev.OIDC.IssuerURL) != strings.TrimSpace(next.OIDC.IssuerURL)
case config.SSOProviderTypeSAML:
if prev.SAML == nil || next.SAML == nil {
return true
}
return strings.TrimSpace(prev.SAML.IDPEntityID) != strings.TrimSpace(next.SAML.IDPEntityID) ||
strings.TrimSpace(prev.SAML.IDPMetadataURL) != strings.TrimSpace(next.SAML.IDPMetadataURL) ||
strings.TrimSpace(prev.SAML.IDPMetadataXML) != strings.TrimSpace(next.SAML.IDPMetadataXML) ||
strings.TrimSpace(prev.SAML.IDPSSOURL) != strings.TrimSpace(next.SAML.IDPSSOURL)
default:
return true
}
}
func (r *Router) resolveConfiguredSSOProviderIssuer(provider *config.SSOProvider) string {
if provider == nil {
return ""
}
switch provider.Type {
case config.SSOProviderTypeOIDC:
if provider.OIDC != nil {
if iss := strings.TrimSpace(provider.OIDC.IssuerURL); iss != "" {
return iss
}
}
if r != nil && r.oidcManager != nil {
if svc := r.oidcManager.GetService(provider.ID); svc != nil {
if iss := strings.TrimSpace(svc.snapshot.issuer); iss != "" {
return iss
}
}
}
case config.SSOProviderTypeSAML:
if provider.SAML != nil {
if iss := strings.TrimSpace(provider.SAML.IDPEntityID); iss != "" {
return iss
}
}
if r != nil && r.samlManager != nil {
if svc := r.samlManager.GetService(provider.ID); svc != nil {
if iss := strings.TrimSpace(svc.GetIDPEntityID()); iss != "" {
return iss
}
}
}
if provider.SAML != nil {
if iss := extractSAMLEntityIDFromXML(provider.SAML.IDPMetadataXML); iss != "" {
return iss
}
}
}
return ""
}
func (r *Router) bindSSOProviderOriginalIssuer(provider *config.SSOProvider, failClosedIfUnknown bool) {
if provider == nil {
return
}
authManager := internalauth.GetManager()
if authManager == nil {
return
}
bindSSOProviderOriginalIssuer(authManager, provider.Type, provider.ID, r.resolveConfiguredSSOProviderIssuer(provider), failClosedIfUnknown)
}
func (r *Router) ssoAuthenticationLoadFailed() bool {
return r != nil && r.ssoAuthLoadFailed.Load()
}
+43
View File
@@ -1198,6 +1198,49 @@ func TestHandleCheckoutActivation_AllowsRetryAfterActivationFailure(t *testing.T
}
}
// The purchase return token is a JWT that is decoded before its signature is
// checked, on a public route. A correctly signed one shows it is the size that
// is refused, in the link and in the form.
func TestHandleCheckoutActivation_RejectsOversizedPurchaseReturnToken(t *testing.T) {
handler := createTestHandler(t)
returnToken := issuePurchaseReturnToken(t, handler, "default", strings.Repeat("a", maxPurchaseReturnTokenBytes))
query := "session_id=cs_success&purchase_return_token=" + url.QueryEscape(returnToken)
for _, req := range []*http.Request{
httptest.NewRequest(http.MethodGet, "https://pulse.example.com"+licensePurchaseActivationPath+"?"+query, nil),
httptest.NewRequest(http.MethodPost, "https://pulse.example.com"+licensePurchaseActivationPath, strings.NewReader(query)),
} {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
handler.HandleCheckoutActivation(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("%s status = %d, want %d (body=%q)", req.Method, rec.Code, http.StatusBadRequest, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "expired or is invalid") {
t.Fatalf("%s body = %q, want invalid link message", req.Method, rec.Body.String())
}
}
req := httptest.NewRequest(
http.MethodPost,
"https://pulse.example.com"+licensePurchaseActivationPath,
strings.NewReader(query+"&pad="+strings.Repeat("a", maxLicensePurchaseActivationRequestBytes)),
)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
handler.HandleCheckoutActivation(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("oversized request status = %d, want %d (body=%q)", rec.Code, http.StatusBadRequest, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "request was invalid") {
t.Fatalf("oversized request body = %q, want invalid request message", rec.Body.String())
}
}
func TestHandleCheckoutActivation_RejectsMissingPurchaseReturnToken(t *testing.T) {
handler := createTestHandler(t)
handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})
+11 -1
View File
@@ -42,6 +42,12 @@ const (
selfHostedBillingPurchaseFailed = "failed"
selfHostedBillingPurchaseUnavailable = "unavailable"
purchaseReturnKeyPurpose = "pulse-license-purchase-return"
// The purchase return token is a JWT whose header and claims are
// JSON-decoded before its signature is checked, and the activation route is
// public. Pulse mints the token itself: well under 1 KiB.
maxPurchaseReturnTokenBytes = 8 * 1024
maxLicensePurchaseActivationRequestBytes = 2 * maxPurchaseReturnTokenBytes
)
// Where checkout finishes when this instance has no secure address to return
@@ -491,6 +497,9 @@ func (h *LicenseHandlers) verifiedPurchaseReturnClaims(
r *http.Request,
returnToken string,
) (*purchaseReturnClaimsModel, error) {
if len(returnToken) > maxPurchaseReturnTokenBytes {
return nil, fmt.Errorf("purchase return token exceeds %d bytes", maxPurchaseReturnTokenBytes)
}
expectedHost := purchaseReturnExpectedHost(r, h.cfg)
if expectedHost == "" {
return nil, fmt.Errorf("purchase return expected host is unavailable")
@@ -1036,7 +1045,7 @@ func (h *LicenseHandlers) HandleActivateLicense(w http.ResponseWriter, r *http.R
}
var req ActivateLicenseRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64*1024)).Decode(&req); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ActivateLicenseResponse{
@@ -1238,6 +1247,7 @@ func (h *LicenseHandlers) HandleCheckoutActivation(w http.ResponseWriter, r *htt
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxLicensePurchaseActivationRequestBytes)
if err := r.ParseForm(); err != nil {
writeLicensePurchaseActivationFailurePage(w, http.StatusBadRequest, "", selfHostedBillingPurchaseFailed, "Purchase activation request was invalid.")
return
+1 -1
View File
@@ -185,7 +185,7 @@ type SetLogLevelRequest struct {
// HandleSetLevel changes the log level at runtime and persists it
func (h *LogHandlers) HandleSetLevel(w http.ResponseWriter, r *http.Request) {
var req SetLogLevelRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
+65
View File
@@ -281,3 +281,68 @@ func TestNoAuthLoopbackAccessRequiresLocalHostAndSameOrigin(t *testing.T) {
})
}
}
// A hosted runtime has no operator on its own host: its users arrive through
// the control plane handoff and it never goes through first-run setup. What
// reaches its loopback port are the requests it sends for its tenants (webhook
// and Apprise tests), so a runtime without local credentials must not serve
// them as the anonymous administrator or hand them recovery.
func TestHostedRuntimeGivesLoopbackNoTrust(t *testing.T) {
t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")
resetTrustedProxyConfig()
adminRequests := []struct {
name string
method string
path string
body string
}{
{name: "list API tokens", method: http.MethodGet, path: "/api/security/tokens"},
{name: "change system settings", method: http.MethodPost, path: "/api/system/settings/update", body: `{"webhookAllowedPrivateCIDRs":"127.0.0.0/8"}`},
{name: "register an SSO provider", method: http.MethodPost, path: "/api/security/sso/providers", body: `{"id":"x","name":"x","type":"oidc","enabled":true}`},
}
t.Run("hosted", func(t *testing.T) {
router := newConfigTransferTestRouter(t, true, nil)
if CheckAuth(router.config, httptest.NewRecorder(), newLoopbackTrustRequest(http.MethodGet, "/api/state", "localhost:7655", nil, "")) {
t.Fatal("hosted runtime admitted a loopback request without credentials")
}
for _, tc := range adminRequests {
req := newLoopbackTrustRequest(tc.method, tc.path, "127.0.0.1:7655", nil, tc.body)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("%s: status = %d, want %d (%s)", tc.name, rec.Code, http.StatusUnauthorized, rec.Body.String())
}
}
for _, action := range []string{"generate_token", "disable_auth"} {
req := newLoopbackTrustRequest(http.MethodPost, "/api/security/recovery", "127.0.0.1:7655", nil, `{"action":"`+action+`"}`)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Errorf("recovery %s: status = %d, want %d (%s)", action, rec.Code, http.StatusForbidden, rec.Body.String())
}
if strings.Contains(rec.Body.String(), `"token"`) {
t.Errorf("recovery %s: token issued: %s", action, rec.Body.String())
}
for _, cookie := range rec.Result().Cookies() {
if cookie.Name == cookieNameSession || cookie.Name == cookieNameSessionSecure {
t.Errorf("recovery %s: session cookie issued", action)
}
}
}
})
t.Run("self-hosted before first-run setup", func(t *testing.T) {
router := newConfigTransferTestRouter(t, false, nil)
req := newLoopbackTrustRequest(http.MethodGet, "/api/security/tokens", "127.0.0.1:7655", nil, "")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want the console lane to stay open (%s)", rec.Code, rec.Body.String())
}
})
}
+6 -2
View File
@@ -63,6 +63,10 @@ type maintenanceVerificationReviewRequest struct {
Note string `json:"note,omitempty"`
}
// maxMaintenanceVerificationReviewRequestBytes bounds the review body, which
// carries only the operator's review note and is persisted with the report.
const maxMaintenanceVerificationReviewRequestBytes = 64 << 10
// MaintenanceVerificationHandlers serves the Maintenance Verification
// Report endpoints. Composes the resource store (for read/write of
// LoopReport rows) with the sentinel runtime (for "rerun" requests).
@@ -177,7 +181,7 @@ func (h *MaintenanceVerificationHandlers) HandleReview(w http.ResponseWriter, r
}
var payload maintenanceVerificationReviewRequest
if r.Body != nil && r.ContentLength != 0 {
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxMaintenanceVerificationReviewRequestBytes)).Decode(&payload); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
@@ -245,7 +249,7 @@ func (h *MaintenanceVerificationHandlers) HandleRerun(w http.ResponseWriter, r *
http.Error(w, "Resource ID required", http.StatusBadRequest)
return
}
report, err := h.sentinel.EvaluateOnce(r.Context(), resourceID)
report, err := h.sentinel.EvaluateOnce(r.Context(), GetOrgID(r.Context()), resourceID)
if err != nil {
if isMaintenanceWindowMissing(err) {
writeJSONError(w, http.StatusBadRequest, "maintenance_window_missing", err.Error())
@@ -1,10 +1,12 @@
package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
@@ -106,6 +108,69 @@ func TestMaintenanceVerification_RerunWritesReport(t *testing.T) {
}
}
func TestMaintenanceVerification_RerunIsScopedToRequestOrg(t *testing.T) {
h, defaultStore := newMaintenanceVerificationFixture(t)
acmeStore, err := h.resources.getStore("acme")
if err != nil {
t.Fatalf("get acme store: %v", err)
}
now := time.Date(2026, 5, 12, 12, 0, 0, 0, time.UTC)
seedMaintenanceWindow(t, defaultStore, "vm:101", now.Add(-time.Hour), now.Add(-15*time.Minute))
rerunAsAcme := func() *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/resources/vm:101/maintenance-verifications/rerun", nil)
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "acme"))
h.HandleRerun(rec, req)
return rec
}
countReports := func(store unified.ResourceStore) int {
t.Helper()
reports, err := store.ListLoopReportsForResource(unified.LoopReportTypeMaintenanceVerification, "vm:101", 0)
if err != nil {
t.Fatalf("list: %v", err)
}
return len(reports)
}
// The window belongs to the default org. A rerun authorized for
// another org must neither disclose it nor add to its history.
rec := rerunAsAcme()
if rec.Code != http.StatusBadRequest {
t.Fatalf("cross-org rerun status = %d body=%s", rec.Code, rec.Body.String())
}
var body map[string]string
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("body must be JSON: %v", err)
}
if body["error"] != "maintenance_window_missing" {
t.Fatalf("error code = %q want maintenance_window_missing", body["error"])
}
if got := countReports(defaultStore); got != 0 {
t.Fatalf("cross-org rerun wrote %d reports into the default org", got)
}
acmeEnd := now.Add(-2 * time.Hour)
seedMaintenanceWindow(t, acmeStore, "vm:101", now.Add(-3*time.Hour), acmeEnd)
rec = rerunAsAcme()
if rec.Code != http.StatusOK {
t.Fatalf("acme rerun status = %d body=%s", rec.Code, rec.Body.String())
}
var report maintenanceVerificationReportAPI
if err := json.Unmarshal(rec.Body.Bytes(), &report); err != nil {
t.Fatalf("parse: %v", err)
}
if report.WindowEndedAt == nil || !report.WindowEndedAt.Equal(acmeEnd) {
t.Fatalf("window end = %v, want acme's %v", report.WindowEndedAt, acmeEnd)
}
if got := countReports(acmeStore); got != 1 {
t.Fatalf("acme reports = %d, want 1", got)
}
if got := countReports(defaultStore); got != 0 {
t.Fatalf("acme rerun wrote %d reports into the default org", got)
}
}
func TestMaintenanceVerification_RerunWithoutWindowReturns400(t *testing.T) {
h, _ := newMaintenanceVerificationFixture(t)
rec := httptest.NewRecorder()
@@ -161,6 +226,45 @@ func TestMaintenanceVerification_ReviewMarksReportReviewed(t *testing.T) {
}
}
func TestMaintenanceVerification_ReviewRejectsOversizedBody(t *testing.T) {
h, store := newMaintenanceVerificationFixture(t)
now := time.Date(2026, 5, 12, 12, 0, 0, 0, time.UTC)
seedMaintenanceWindow(t, store, "vm:101", now.Add(-time.Hour), now.Add(-15*time.Minute))
rerunRec := httptest.NewRecorder()
rerunReq := withDefaultOrg(httptest.NewRequest(http.MethodPost, "/api/resources/vm:101/maintenance-verifications/rerun", nil))
h.HandleRerun(rerunRec, rerunReq)
if rerunRec.Code != http.StatusOK {
t.Fatalf("rerun status = %d body=%s", rerunRec.Code, rerunRec.Body.String())
}
var seeded maintenanceVerificationReportAPI
if err := json.Unmarshal(rerunRec.Body.Bytes(), &seeded); err != nil {
t.Fatalf("parse rerun: %v", err)
}
body, _ := json.Marshal(map[string]string{
"note": strings.Repeat("a", maxMaintenanceVerificationReviewRequestBytes),
})
rec := httptest.NewRecorder()
req := withDefaultOrg(httptest.NewRequest(
http.MethodPost,
"/api/maintenance-verifications/"+seeded.ID+"/review",
bytes.NewReader(body),
))
h.HandleReview(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400 on oversized body, got %d", rec.Code)
}
persisted, found, err := store.GetLoopReport(seeded.ID)
if err != nil || !found {
t.Fatalf("get report: found=%v err=%v", found, err)
}
if persisted.UserOutcome == unified.LoopReportUserOutcomeReviewed || persisted.ReviewNote != "" {
t.Fatalf("oversized review must not persist; outcome=%q note length=%d", persisted.UserOutcome, len(persisted.ReviewNote))
}
}
func TestMaintenanceVerification_ReviewMissingReportReturns404(t *testing.T) {
h, _ := newMaintenanceVerificationFixture(t)
rec := httptest.NewRecorder()
+30 -1
View File
@@ -4,6 +4,7 @@ import (
"bufio"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"runtime/debug"
@@ -44,6 +45,13 @@ func (e *APIError) Error() string {
// ErrorHandler is a middleware that handles panics and errors
func ErrorHandler(next http.Handler) http.Handler {
return errorHandler(next, func(r *http.Request) string { return normalizeRoute(r.URL.Path) })
}
// errorHandler is ErrorHandler with the caller choosing the route label of the
// HTTP metrics. The label must come from a fixed set when clients choose the
// paths: every new label is a set of metric series kept until the process exits.
func errorHandler(next http.Handler, metricRoute func(*http.Request) string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Fix for issue #334: Normalize empty path to "/" before ServeMux processes it
// This prevents the automatic redirect from "" to "./"
@@ -65,9 +73,11 @@ func ErrorHandler(next http.Handler) http.Handler {
// Create a custom response writer to capture status codes
rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
rw.Header().Set("X-Request-ID", requestID)
// A body can outlive the credential that admitted its headers.
r, rw.bodyAuthority = withRequestBodyAuthority(r)
start := time.Now()
routeLabel := normalizeRoute(r.URL.Path)
routeLabel := metricRoute(r)
method := r.Method
defer func() {
@@ -93,6 +103,10 @@ func ErrorHandler(next http.Handler) http.Handler {
// Call the next handler
next.ServeHTTP(rw, r)
// A handler that wrote nothing must not imply 200 after withdrawal.
if rw.bodyAuthority.refused() {
rw.WriteHeader(http.StatusOK)
}
// A 5xx is ours to explain, so it warns. A 4xx is the client being told
// no — an unauthenticated bootstrap request, an RBAC refusal, a probe for
@@ -166,6 +180,11 @@ type responseWriter struct {
http.ResponseWriter
statusCode int
written bool
// bodyAuthority is nil for bodyless requests. Once a body read finds the
// admitted credential withdrawn, an unstarted response becomes the
// generic 401 and the handler's own output is dropped.
bodyAuthority *requestBodyAuthority
refused bool
}
// Keep ResponseController deadline operations available to streaming handlers.
@@ -181,6 +200,13 @@ func (rw *responseWriter) SetReadDeadline(deadline time.Time) error {
func (rw *responseWriter) WriteHeader(code int) {
if !rw.written {
if rw.bodyAuthority.refused() {
rw.statusCode = http.StatusUnauthorized
rw.written = true
rw.refused = true
http.Error(rw.ResponseWriter, "Authentication required", http.StatusUnauthorized)
return
}
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
rw.written = true
@@ -191,6 +217,9 @@ func (rw *responseWriter) Write(b []byte) (int, error) {
if !rw.written {
rw.WriteHeader(http.StatusOK)
}
if rw.refused {
return 0, io.ErrClosedPipe
}
return rw.ResponseWriter.Write(b)
}
+2 -2
View File
@@ -181,7 +181,7 @@ func (r *Router) handleMonitoredSystemLedger(w http.ResponseWriter, req *http.Re
func (r *Router) handleMonitoredSystemLedgerPreview(w http.ResponseWriter, req *http.Request) {
var previewReq MonitoredSystemLedgerPreviewRequest
decoder := json.NewDecoder(req.Body)
decoder := json.NewDecoder(http.MaxBytesReader(w, req.Body, 64*1024))
if err := decoder.Decode(&previewReq); err != nil {
writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", map[string]string{"error": err.Error()})
return
@@ -225,7 +225,7 @@ func (r *Router) handleMonitoredSystemLedgerPreview(w http.ResponseWriter, req *
func (r *Router) handleMonitoredSystemLedgerExplain(w http.ResponseWriter, req *http.Request) {
var explainReq MonitoredSystemLedgerExplainRequest
decoder := json.NewDecoder(req.Body)
decoder := json.NewDecoder(http.MaxBytesReader(w, req.Body, 64*1024))
if err := decoder.Decode(&explainReq); err != nil && err != io.EOF {
writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", map[string]string{"error": err.Error()})
return
+185
View File
@@ -0,0 +1,185 @@
package api
import (
"crypto/rand"
"crypto/rsa"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
jose "github.com/go-jose/go-jose/v4"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
func TestOIDCEmailUnverified(t *testing.T) {
for _, tc := range []struct {
name string
claims map[string]any
emailClaim string
want bool
}{
{"verified", map[string]any{"email_verified": true}, "email", false},
{"unverified", map[string]any{"email_verified": false}, "email", true},
{"verified as text", map[string]any{"email_verified": " True "}, "email", false},
{"unverified as text", map[string]any{"email_verified": "false"}, "email", true},
{"not a boolean", map[string]any{"email_verified": float64(1)}, "email", true},
{"omitted", map[string]any{}, "email", false},
{"null", map[string]any{"email_verified": nil}, "email", false},
{"address mapped from another claim", map[string]any{"email_verified": false}, "upn", false},
} {
t.Run(tc.name, func(t *testing.T) {
if got := oidcEmailUnverified(tc.claims, tc.emailClaim); got != tc.want {
t.Fatalf("oidcEmailUnverified = %v, want %v", got, tc.want)
}
})
}
}
// runOIDCEmailVerifiedCallback signs in once through the real login and
// callback handlers against a guest-local provider that issues extra as the
// user's claims, and returns where the callback sent the browser. All
// identities and keys are synthetic.
func runOIDCEmailVerifiedCallback(t *testing.T, key *rsa.PrivateKey, manager internalauth.Manager, configure func(*config.SSOProvider), extra map[string]any) string {
t.Helper()
resetPersistentAuthStoresForTests()
t.Cleanup(resetPersistentAuthStoresForTests)
InitPersistentAuthStores(t.TempDir())
previousManager := internalauth.GetManager()
internalauth.SetManager(manager)
t.Cleanup(func() { internalauth.SetManager(previousManager) })
jwks, err := json.Marshal(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: key.Public(), KeyID: "synthetic-email", Use: "sig", Algorithm: "RS256"}}})
if err != nil {
t.Fatal(err)
}
var authorization url.Values
idp := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
base := "http://" + req.Host
switch req.URL.Path {
case "/.well-known/openid-configuration":
_ = json.NewEncoder(w).Encode(map[string]any{"issuer": base, "authorization_endpoint": base + "/authorize", "token_endpoint": base + "/token", "jwks_uri": base + "/jwks", "id_token_signing_alg_values_supported": []string{"RS256"}})
case "/jwks":
_, _ = w.Write(jwks)
case "/token":
claims := map[string]any{"iss": base, "aud": authorization.Get("client_id"), "sub": "synthetic-subject", "nonce": authorization.Get("nonce"), "iat": time.Now().Add(-time.Minute).Unix(), "exp": time.Now().Add(time.Hour).Unix()}
for name, value := range extra {
claims[name] = value
}
signed := signOIDCJOSEFixture(t, key, "RS256", "synthetic-email", claims, false)
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "synthetic-access", "id_token": signed, "token_type": "Bearer", "expires_in": 3600})
default:
http.NotFound(w, req)
}
}))
t.Cleanup(idp.Close)
r, _ := setupTestRouter(t)
r.config.PublicURL = "https://pulse.example.test"
p := newRecoveryTestProvider("email-verified", true, "")
p.OIDC.IssuerURL = idp.URL
configure(&p)
if err := r.ssoConfig.AddProvider(p); err != nil {
t.Fatal(err)
}
if err := r.saveSSOConfig(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { r.oidcManager.RemoveService(p.ID) })
login := httptest.NewRecorder()
r.handleSSOOIDCLogin(login, httptest.NewRequest("GET", "https://pulse.example.test/api/oidc/"+p.ID+"/login?returnTo=/alerts", nil))
authURL, err := url.Parse(login.Header().Get("Location"))
if err != nil || authURL.Query().Get("state") == "" {
t.Fatalf("native login failed: %d %v", login.Code, err)
}
authorization = authURL.Query()
target := "https://pulse.example.test/api/oidc/" + p.ID + "/callback?code=synthetic-code&state=" + url.QueryEscape(authorization.Get("state"))
return doOIDCCallback(t, r, target).Header().Get("Location")
}
// An address the provider itself reports as unverified is text the account
// holder typed. It must not satisfy a restriction on who may sign in.
func TestSSOOIDCCallbackEmailRestrictionsRequireVerifiedEmail(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
const success, refused = "/alerts?oidc=success", "/alerts?oidc=error&oidc_error=email_unverified"
domains := func(p *config.SSOProvider) { p.AllowedDomains = []string{"corp.example.test"} }
emails := func(p *config.SSOProvider) { p.AllowedEmails = []string{"mallory@corp.example.test"} }
for _, tc := range []struct {
name string
configure func(*config.SSOProvider)
claims map[string]any
want string
}{
{"domain list, verified", domains, map[string]any{"email": "alice@corp.example.test", "email_verified": true}, success},
{"domain list, provider omits email_verified", domains, map[string]any{"email": "alice@corp.example.test"}, success},
{"domain list, unverified", domains, map[string]any{"email": "mallory@corp.example.test", "email_verified": false}, refused},
{"domain list, unverified as text", domains, map[string]any{"email": "mallory@corp.example.test", "email_verified": "false"}, refused},
{"email list, unverified", emails, map[string]any{"email": "mallory@corp.example.test", "email_verified": false}, refused},
{"email list, verified", emails, map[string]any{"email": "mallory@corp.example.test", "email_verified": true}, success},
{"domain list, verified elsewhere", domains, map[string]any{"email": "outsider@elsewhere.example.test", "email_verified": true}, "/alerts?oidc=error&oidc_error=domain_restricted"},
{"domain list, address mapped from another claim", func(p *config.SSOProvider) { domains(p); p.OIDC.EmailClaim = "upn" }, map[string]any{"upn": "alice@corp.example.test", "email_verified": false}, success},
{"no email restriction, unverified", func(*config.SSOProvider) {}, map[string]any{"email": "mallory@corp.example.test", "email_verified": false}, success},
} {
t.Run(tc.name, func(t *testing.T) {
manager, err := internalauth.NewFileManager(t.TempDir())
if err != nil {
t.Fatal(err)
}
if got := runOIDCEmailVerifiedCallback(t, key, manager, tc.configure, tc.claims); got != tc.want {
t.Fatalf("callback redirected to %q, want %q", got, tc.want)
}
})
}
}
// Roles saved under an address before stable principals existed move to the
// subject that signs in with that address. An unverified address must not
// claim them, including when another claim repeats it or it stands in for a
// missing username.
func TestSSOOIDCCallbackUnverifiedEmailDoesNotClaimLegacyRoles(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
const legacy = "admin@corp.example.test"
for _, tc := range []struct {
name string
claims map[string]any
migrates bool
}{
{"verified", map[string]any{"email": legacy, "email_verified": true}, true},
{"provider omits email_verified", map[string]any{"email": legacy}, true},
{"unverified", map[string]any{"email": legacy, "email_verified": false}, false},
{"unverified, address as username", map[string]any{"email": legacy, "preferred_username": "Admin@Corp.Example.Test", "email_verified": false}, false},
{"unverified, address as display name", map[string]any{"email": legacy, "preferred_username": "mallory", "name": legacy, "email_verified": false}, false},
} {
t.Run(tc.name, func(t *testing.T) {
manager, err := internalauth.NewFileManager(t.TempDir())
if err != nil {
t.Fatal(err)
}
if err := manager.UpdateUserRoles(legacy, []string{internalauth.RoleAdmin}); err != nil {
t.Fatal(err)
}
if got := runOIDCEmailVerifiedCallback(t, key, manager, func(*config.SSOProvider) {}, tc.claims); got != "/alerts?oidc=success" {
t.Fatalf("callback redirected to %q", got)
}
principal, err := stableSSOPrincipal(config.SSOProviderTypeOIDC, "email-verified", "synthetic-subject")
if err != nil {
t.Fatal(err)
}
assignment, _ := manager.GetUserAssignment(principal)
if migrated := len(assignment.RoleIDs) > 0; migrated != tc.migrates {
t.Fatalf("principal roles = %v, want migration %v", assignment.RoleIDs, tc.migrates)
}
})
}
}
+52 -2
View File
@@ -3,10 +3,12 @@ package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"sort"
"strings"
"time"
@@ -139,6 +141,28 @@ func extractStringSliceClaim(claims map[string]any, key string) []string {
}
}
// oidcEmailUnverified reports whether the provider states that the address in
// the standard email claim is not verified. Such an address is whatever the
// account holder typed, so it identifies nobody. A provider that omits
// email_verified makes no such statement, and the claim does not describe an
// address an administrator maps from another claim; both stay as they were.
func oidcEmailUnverified(claims map[string]any, emailClaim string) bool {
if emailClaim != "email" {
return false
}
switch verified := claims["email_verified"].(type) {
case nil:
return false
case bool:
return !verified
case string:
// Some providers send the boolean as text.
return !strings.EqualFold(strings.TrimSpace(verified), "true")
default:
return true
}
}
func matchesValue(candidate string, allowed []string) bool {
candidate = strings.ToLower(strings.TrimSpace(candidate))
if candidate == "" {
@@ -648,7 +672,14 @@ func (r *Router) handleSSOOIDCCallback(w http.ResponseWriter, req *http.Request)
if username == "" {
username = idToken.Subject
}
principal, err := stableSSOPrincipal(config.SSOProviderTypeOIDC, providerID, idToken.Subject)
// The subject belongs to the issuer this service's verifier just admitted
// the ID token for. Name that issuer URL rather than the raw iss claim:
// go-oidc also accepts Google's scheme-less spelling for the same accounts.
verifiedIssuer := strings.TrimSpace(service.snapshot.issuer)
if verifiedIssuer == "" && provider.OIDC != nil {
verifiedIssuer = strings.TrimSpace(provider.OIDC.IssuerURL)
}
principal, err := stableSSOPrincipalForIssuer(internalauth.GetManager(), config.SSOProviderTypeOIDC, providerID, verifiedIssuer, idToken.Subject)
if err != nil {
log.Error().Err(err).Str("provider_id", providerID).Msg("OIDC subject is not usable as a stable SSO principal")
LogAuditEventForTenant(GetOrgID(req.Context()), "sso_oidc_login", username, GetClientIP(req), req.URL.Path, false, "Missing stable OIDC subject")
@@ -657,6 +688,12 @@ func (r *Router) handleSSOOIDCCallback(w http.ResponseWriter, req *http.Request)
}
// Apply access restrictions from SSO provider config
emailUnverified := oidcEmailUnverified(claims, emailClaim)
if emailUnverified && (len(provider.AllowedEmails) > 0 || len(provider.AllowedDomains) > 0) {
LogAuditEventForTenant(GetOrgID(req.Context()), "sso_oidc_login", email, GetClientIP(req), req.URL.Path, false, "Email not verified by the provider")
r.redirectOIDCError(w, req, entry.ReturnTo, "email_unverified")
return
}
if len(provider.AllowedEmails) > 0 && !matchesValue(email, provider.AllowedEmails) {
LogAuditEventForTenant(GetOrgID(req.Context()), "sso_oidc_login", email, GetClientIP(req), req.URL.Path, false, "Email not permitted")
r.redirectOIDCError(w, req, entry.ReturnTo, "email_restricted")
@@ -685,9 +722,22 @@ func (r *Router) handleSSOOIDCCallback(w http.ResponseWriter, req *http.Request)
if authManager := internalauth.GetManager(); authManager != nil {
groups := extractStringSliceClaim(claims, provider.GroupsClaim)
rolesToAssign := resolveGroupRoles(groups, provider.GroupRoleMappings)
legacyCandidates := ssoLegacyPrincipalCandidates(username, email, extractStringClaim(claims, "name"))
// Pre-principal assignments were keyed by the resolved username,
// which already falls back to email and then the display name. A
// separately supplied free-form name claim was never a lookup key.
legacyCandidates := ssoLegacyPrincipalCandidates(username, email)
if emailUnverified {
// Legacy assignments may be keyed by an address. One the provider
// has not verified is no key to them, whichever claim carries it.
legacyCandidates = slices.DeleteFunc(legacyCandidates, func(candidate string) bool {
return strings.EqualFold(candidate, email)
})
}
if err := applySSORoleAssignments(authManager, principal, legacyCandidates, rolesToAssign, len(provider.GroupRoleMappings) > 0, true); err != nil {
log.Error().Err(err).Str("user", principal).Str("display_user", username).Msg("Failed to update SSO OIDC user roles")
if errors.Is(err, errSSORolesNotReplaced) {
return err
}
} else if len(rolesToAssign) > 0 {
LogAuditEventForTenant(GetOrgID(req.Context()), "sso_oidc_role_assignment", principal, GetClientIP(req), req.URL.Path, true, "Auto-assigned roles: "+strings.Join(rolesToAssign, ", "))
}
+1 -1
View File
@@ -135,7 +135,7 @@ func (r *Router) handleValidateOnboardingConnection(w http.ResponseWriter, req *
}
var payload onboardingValidationRequest
decoder := json.NewDecoder(req.Body)
decoder := json.NewDecoder(http.MaxBytesReader(w, req.Body, 16*1024))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&payload); err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
+1 -1
View File
@@ -97,7 +97,7 @@ var orgAccessRecheckInterval = 10 * time.Second
// signed-in user's long-lived read (WebSocket or SSE). Membership removal,
// default-organization revocation and losing instance administration end the
// stream within orgAccessRecheckInterval. Token readers keep their own
// credential revalidation, which already rechecks organization bindings.
// credential revalidation, which rechecks the token against this policy.
// It returns nil when the request has no user to recheck.
func orgAccessRevalidator(req *http.Request) func() bool {
return orgAccessRevalidatorWithInterval(req, orgAccessRecheckInterval)
@@ -75,6 +75,7 @@ func TestInstanceSettingsScopeRequiresInstanceWideToken(t *testing.T) {
}{
{"ensureSettingsReadScope", ensureSettingsReadScope, binding.instance && hasSettings},
{"ensureSettingsWriteScope", ensureSettingsWriteScope, binding.instance && hasSettings},
{"ensureSSOProviderWrite", ensureSSOProviderWrite, binding.instance && scopes[0] == config.ScopeWildcard},
{"ensureOrgSettingsWriteScope", ensureOrgSettingsWriteScope, hasSettings},
{"ensureAdminSession", ensureAdminSession, binding.instance},
{"ensureOrgAdminSession", ensureOrgAdminSession, true},
@@ -167,7 +168,6 @@ func TestOrgBoundSettingsTokenRouterMatrix(t *testing.T) {
instanceRoutes := []struct{ method, path string }{
{http.MethodPost, "/api/system/settings/update"},
{http.MethodGet, "/api/system/settings"},
{http.MethodPost, "/api/security/sso/providers"},
{http.MethodGet, "/api/security/sso/providers"},
{http.MethodGet, "/api/security/tokens"},
{http.MethodPost, "/api/security/tokens"},
+233
View File
@@ -0,0 +1,233 @@
package api
import (
"bytes"
"context"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
)
func newOrgBoundTokenForTest(t *testing.T, id string, age time.Duration, scope, orgID string, orgIDs ...string) config.APITokenRecord {
t.Helper()
record, err := config.NewAPITokenRecord(id+"-raw-token-0123456789abcdef0123456789", id, []string{scope})
if err != nil {
t.Fatalf("NewAPITokenRecord(%s): %v", id, err)
}
record.ID = id
record.CreatedAt = time.Now().UTC().Add(-age)
record.OrgID = orgID
record.OrgIDs = orgIDs
return *record
}
// An organization is identified by an ID that is free to be claimed again once
// the organization is deleted. Its instance API tokens must not survive into
// whichever organization takes the ID next.
func TestCleanupTenantRevokesOrganizationAPITokens(t *testing.T) {
dataDir := t.TempDir()
persistence := config.NewConfigPersistence(dataDir)
cfg := &config.Config{DataPath: dataDir}
cfg.APITokens = []config.APITokenRecord{
newOrgBoundTokenForTest(t, "acme-only", 1*time.Minute, config.ScopeMonitoringRead, "acme"),
newOrgBoundTokenForTest(t, "acme-only-list", 2*time.Minute, config.ScopeMonitoringRead, "", "acme"),
newOrgBoundTokenForTest(t, "acme-list-over-globex", 3*time.Minute, config.ScopeMonitoringRead, "globex", "acme"),
newOrgBoundTokenForTest(t, "acme-and-globex", 4*time.Minute, config.ScopeMonitoringRead, "acme", "acme", "globex"),
newOrgBoundTokenForTest(t, "acme-and-default", 5*time.Minute, config.ScopeWildcard, "", "acme", "default"),
newOrgBoundTokenForTest(t, "globex-only", 6*time.Minute, config.ScopeMonitoringRead, "globex"),
newOrgBoundTokenForTest(t, "default-only", 7*time.Minute, config.ScopeWildcard, "default"),
}
cfg.SortAPITokens()
if err := persistence.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
router := &Router{config: cfg, persistence: persistence}
if err := router.CleanupTenant(context.Background(), "acme"); err != nil {
t.Fatalf("CleanupTenant: %v", err)
}
assertInventory := func(source string, tokens []config.APITokenRecord) {
t.Helper()
var ids []string
for i := range tokens {
ids = append(ids, tokens[i].ID)
if tokens[i].CanAccessOrg("acme") || tokens[i].OrgID == "acme" {
t.Errorf("%s: token %q is still bound to the deleted organization", source, tokens[i].ID)
}
if tokens[i].IsLegacyToken() {
t.Errorf("%s: token %q lost its organization binding instead of being revoked", source, tokens[i].ID)
}
// Only the token that already was instance-wide may remain so.
if tokenActsForInstance(&tokens[i]) != (tokens[i].ID == "default-only") {
t.Errorf("%s: token %q changed whether it acts for the instance", source, tokens[i].ID)
}
}
if want := []string{"acme-and-globex", "globex-only", "default-only"}; !slices.Equal(ids, want) {
t.Fatalf("%s: tokens = %v, want %v", source, ids, want)
}
if !tokens[0].CanAccessOrg("globex") {
t.Errorf("%s: multi-organization token lost its remaining organization", source)
}
}
assertInventory("live", cfg.APITokens)
persisted, err := persistence.LoadAPITokens()
if err != nil {
t.Fatalf("LoadAPITokens: %v", err)
}
assertInventory("persisted", persisted)
}
func TestRevokeTenantCredentialsKeepsInventoryWhenSaveFails(t *testing.T) {
dataDir := t.TempDir()
persistence := config.NewConfigPersistence(dataDir)
cfg := &config.Config{DataPath: dataDir}
cfg.APITokens = []config.APITokenRecord{
newOrgBoundTokenForTest(t, "acme-only", 1*time.Minute, config.ScopeMonitoringRead, "acme"),
newOrgBoundTokenForTest(t, "globex-only", 2*time.Minute, config.ScopeMonitoringRead, "globex"),
}
cfg.SortAPITokens()
if err := persistence.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
// A real write refusal, confined to this disposable test directory.
tokensPath := filepath.Join(dataDir, "api_tokens.json")
if err := os.Remove(tokensPath); err != nil {
t.Fatalf("remove token file: %v", err)
}
if err := os.MkdirAll(filepath.Join(tokensPath, "blocked"), 0o700); err != nil {
t.Fatalf("block token file: %v", err)
}
router := &Router{config: cfg, persistence: persistence}
if err := router.revokeTenantCredentials("acme"); err == nil {
t.Fatal("expected an error when the token inventory cannot be saved")
}
if len(cfg.APITokens) != 2 || !cfg.APITokens[0].CanAccessOrg("acme") {
t.Fatalf("live inventory changed although the revocation was not persisted: %+v", cfg.APITokens)
}
}
func TestOrgHandlersDeleteRetainsOrgWhenCredentialRevocationFails(t *testing.T) {
t.Setenv("PULSE_DEV", "true")
defer SetMultiTenantEnabled(false)
SetMultiTenantEnabled(true)
persistence := config.NewMultiTenantPersistence(t.TempDir())
h := NewOrgHandlers(persistence, nil)
revocationErr := errors.New("token inventory unavailable")
var order []string
h.SetCredentialRevoker(func(orgID string) error {
if !persistence.OrgExists(orgID) {
t.Errorf("credentials must be revoked before organization %q is removed", orgID)
}
order = append(order, "before")
return revocationErr
})
h.SetOnDelete(func(_ context.Context, _ string) error {
order = append(order, "after")
return nil
})
if err := persistence.SaveOrganization(&models.Organization{ID: "acme", DisplayName: "Acme Corp", OwnerUserID: "alice"}); err != nil {
t.Fatalf("SaveOrganization: %v", err)
}
deleteOrg := func() int {
req := withUser(httptest.NewRequest(http.MethodDelete, "/api/orgs/acme", nil), "alice")
req.SetPathValue("id", "acme")
rec := httptest.NewRecorder()
h.HandleDeleteOrg(rec, req)
return rec.Code
}
if code := deleteOrg(); code != http.StatusInternalServerError {
t.Fatalf("expected 500 when credentials cannot be revoked, got %d", code)
}
if !persistence.OrgExists("acme") {
t.Fatal("organization was deleted although its credentials are still valid")
}
if !slices.Equal(order, []string{"before"}) {
t.Fatalf("callbacks = %v, want only the pre-delete callback", order)
}
revocationErr = nil
order = nil
if code := deleteOrg(); code != http.StatusNoContent {
t.Fatalf("expected 204 once credentials are revoked, got %d", code)
}
if persistence.OrgExists("acme") {
t.Fatal("organization still exists after a successful delete")
}
if !slices.Equal(order, []string{"before", "after"}) {
t.Fatalf("callbacks = %v, want before then after", order)
}
}
// Tokens orphaned by an organization that was deleted before deletion revoked
// them, or whose directory was removed by hand, are still bound to its ID. A
// new organization must not start out with them.
func TestOrgHandlersCreateRevokesCredentialsLeftOnTheID(t *testing.T) {
t.Setenv("PULSE_DEV", "true")
defer SetMultiTenantEnabled(false)
SetMultiTenantEnabled(true)
dataDir := t.TempDir()
cfg := &config.Config{DataPath: dataDir}
cfg.APITokens = []config.APITokenRecord{
newOrgBoundTokenForTest(t, "old-acme", 1*time.Minute, config.ScopeMonitoringRead, "acme"),
newOrgBoundTokenForTest(t, "globex-only", 2*time.Minute, config.ScopeMonitoringRead, "globex"),
}
cfg.SortAPITokens()
router := &Router{config: cfg, persistence: config.NewConfigPersistence(dataDir)}
persistence := config.NewMultiTenantPersistence(dataDir)
h := NewOrgHandlers(persistence, nil)
var revocationErr error
h.SetCredentialRevoker(func(orgID string) error {
if persistence.OrgExists(orgID) {
t.Errorf("credentials must be revoked before organization %q exists", orgID)
}
if revocationErr != nil {
return revocationErr
}
return router.revokeTenantCredentials(orgID)
})
createOrg := func() int {
body := bytes.NewBufferString(`{"id":"acme","displayName":"New Acme"}`)
req := withUser(httptest.NewRequest(http.MethodPost, "/api/orgs", body), "bob")
rec := httptest.NewRecorder()
h.HandleCreateOrg(rec, req)
return rec.Code
}
revocationErr = errors.New("token inventory unavailable")
if code := createOrg(); code != http.StatusInternalServerError {
t.Fatalf("expected 500 when stale credentials cannot be revoked, got %d", code)
}
if persistence.OrgExists("acme") {
t.Fatal("organization was created although stale credentials are still bound to its ID")
}
revocationErr = nil
if code := createOrg(); code != http.StatusCreated {
t.Fatalf("expected 201 once stale credentials are revoked, got %d", code)
}
if len(cfg.APITokens) != 1 || cfg.APITokens[0].ID != "globex-only" {
t.Fatalf("tokens after create = %+v, want only globex-only", cfg.APITokens)
}
}
+89
View File
@@ -12,6 +12,7 @@ import (
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
@@ -26,6 +27,19 @@ const (
licenseFeatureMultiTenantKey = "multi_tenant"
)
// maxOwnedOrganizations bounds the organizations one user below instance
// administrator may own. An organization is not just its org.json: it gets a
// monitor with its own alert manager, notification manager and stores,
// started when it is first used and again by the report scheduler after every
// restart. Without a bound, any signed-in user could exhaust the server's
// memory with small requests, and the saved organizations would exhaust it
// again on every start.
const maxOwnedOrganizations = 20
// orgOwnershipMu serializes counting a user's organizations and saving the
// one that adds to them, so parallel requests cannot pass the limit together.
var orgOwnershipMu sync.Mutex
var organizationIDPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
var supportedOrganizationShareResourceTypes = map[string]struct{}{
@@ -94,6 +108,8 @@ type OrgHandlers struct {
onDelete func(ctx context.Context, orgID string) error
hostedMode bool
accessPolicy *DefaultAuthorizationChecker
// revokeCredentials withdraws the credentials bound to an org ID.
revokeCredentials func(orgID string) error
}
func NewOrgHandlers(
@@ -113,6 +129,18 @@ func NewOrgHandlers(
}
}
// SetCredentialRevoker configures an optional callback that withdraws the
// credentials bound to an org ID. It runs before an org's data is removed and
// before a free ID is claimed by a new org, and an error aborts either:
// credentials are matched to an org by ID alone and must not pass from one
// holder of an ID to the next.
func (h *OrgHandlers) SetCredentialRevoker(callback func(orgID string) error) {
if h == nil {
return
}
h.revokeCredentials = callback
}
// SetOnDelete configures an optional callback invoked after org deletion.
func (h *OrgHandlers) SetOnDelete(callback func(ctx context.Context, orgID string) error) {
if h == nil {
@@ -367,10 +395,26 @@ func (h *OrgHandlers) HandleCreateOrg(w http.ResponseWriter, r *http.Request) {
writeErrorResponse(w, http.StatusBadRequest, "invalid_display_name", "Display name is required", nil)
return
}
orgOwnershipMu.Lock()
defer orgOwnershipMu.Unlock()
if h.persistence.OrgExists(req.ID) {
writeErrorResponse(w, http.StatusConflict, "already_exists", "Organization already exists", nil)
return
}
if !h.admitOrganizationOwner(w, r, username) {
return
}
// Credentials still bound to a free ID belong to an organization that no
// longer exists (deleted before deletion revoked them, or removed outside
// the API). They must not carry over to this one.
if h.revokeCredentials != nil {
if err := h.revokeCredentials(req.ID); err != nil {
log.Error().Err(err).Str("org_id", req.ID).Msg("Failed to revoke credentials left bound to organization ID; not creating it")
writeErrorResponse(w, http.StatusInternalServerError, "create_failed", "Failed to create organization", nil)
return
}
}
now := time.Now().UTC()
org := &models.Organization{
@@ -396,6 +440,36 @@ func (h *OrgHandlers) HandleCreateOrg(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, org)
}
// admitOrganizationOwner reports whether owner may own one more organization,
// and writes the refusal when not. The limit binds users below instance
// administrator in what they create and what they hand to each other;
// instance administrators set up the organizations of a multi-organization
// instance and may create, receive and hand over any number. The caller holds
// orgOwnershipMu until the organization is saved.
func (h *OrgHandlers) admitOrganizationOwner(w http.ResponseWriter, r *http.Request, owner string) bool {
if h.accessPolicy != nil && h.accessPolicy.instanceAdmin != nil {
if h.accessPolicy.instanceAdmin(r.Context(), auth.GetUser(r.Context())) || h.accessPolicy.instanceAdmin(r.Context(), owner) {
return true
}
}
orgs, err := h.persistence.ListOrganizations()
if err != nil {
writeErrorResponse(w, http.StatusInternalServerError, "list_failed", "Failed to list organizations", nil)
return false
}
owned := 0
for _, org := range orgs {
if org != nil && org.IsOwnerUserID(owner) {
owned++
}
}
if owned >= maxOwnedOrganizations {
writeErrorResponse(w, http.StatusConflict, "organization_limit_reached", fmt.Sprintf("A user can own at most %d organizations", maxOwnedOrganizations), nil)
return false
}
return true
}
func (h *OrgHandlers) HandleGetOrg(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
@@ -524,6 +598,14 @@ func (h *OrgHandlers) HandleDeleteOrg(w http.ResponseWriter, r *http.Request) {
defer h.mtMonitor.FinishTenantDeletion(orgID)
}
if h.revokeCredentials != nil {
if err := h.revokeCredentials(orgID); err != nil {
log.Error().Err(err).Str("org_id", orgID).Msg("Failed to revoke organization credentials; retaining data")
writeErrorResponse(w, http.StatusInternalServerError, "delete_failed", "Failed to delete organization", nil)
return
}
}
if err := h.persistence.DeleteOrganization(orgID); err != nil {
if errors.Is(err, os.ErrNotExist) || errors.Is(err, errOrgNotFound) {
writeErrorResponse(w, http.StatusNotFound, "not_found", "Organization not found", nil)
@@ -655,6 +737,13 @@ func (h *OrgHandlers) HandleInviteMember(w http.ResponseWriter, r *http.Request)
writeErrorResponse(w, authErr.Status, authErr.Code, authErr.Message, nil)
return
}
// A transfer counts against the new owner like a creation, or a
// user could keep creating organizations and handing them on.
orgOwnershipMu.Lock()
defer orgOwnershipMu.Unlock()
if !h.admitOrganizationOwner(w, r, req.UserID) {
return
}
for i := range org.Members {
if org.Members[i].UserID == org.OwnerUserID {
org.Members[i].Role = models.OrgRoleAdmin
+168
View File
@@ -13,6 +13,7 @@ import (
"path/filepath"
"reflect"
"strings"
"sync"
"testing"
"time"
@@ -2030,3 +2031,170 @@ func TestOrgHandlersWriteBodyNativeHTTP(t *testing.T) {
}
}
}
func createOrgForTest(h *OrgHandlers, user, orgID string) int {
req := withUser(httptest.NewRequest(http.MethodPost, "/api/orgs", bytes.NewBufferString(`{"id":"`+orgID+`","displayName":"`+orgID+`"}`)), user)
rec := httptest.NewRecorder()
h.HandleCreateOrg(rec, req)
return rec.Code
}
func transferOrgForTest(h *OrgHandlers, orgID, owner, target string) *httptest.ResponseRecorder {
req := withUser(
httptest.NewRequest(http.MethodPost, "/api/orgs/"+orgID+"/members", bytes.NewBufferString(`{"userId":"`+target+`","role":"owner"}`)),
owner,
)
session := generateSessionToken()
GetSessionStore().CreateSession(session, time.Hour, "browser", "127.0.0.1", owner)
req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: session})
req.SetPathValue("id", orgID)
rec := httptest.NewRecorder()
h.HandleInviteMember(rec, req)
return rec
}
func ownedOrganizationsForTest(t *testing.T, persistence *config.MultiTenantPersistence, user string) int {
t.Helper()
orgs, err := persistence.ListOrganizations()
if err != nil {
t.Fatalf("list organizations: %v", err)
}
owned := 0
for _, org := range orgs {
if org.IsOwnerUserID(user) {
owned++
}
}
return owned
}
func newOrgOwnershipLimitHandlers(t *testing.T) (*OrgHandlers, *config.MultiTenantPersistence) {
t.Helper()
t.Setenv("PULSE_DEV", "true")
previous := IsMultiTenantEnabled()
SetMultiTenantEnabled(true)
t.Cleanup(func() { SetMultiTenantEnabled(previous) })
InitSessionStore(t.TempDir())
persistence := config.NewMultiTenantPersistence(t.TempDir())
checker := NewAuthorizationChecker(NewMultiTenantOrganizationLoader(persistence))
checker.SetInstanceAdminResolver(func(_ context.Context, userID string) bool { return userID == "root" })
h := NewOrgHandlers(persistence, nil)
h.SetAccessPolicy(checker)
return h, persistence
}
func TestOrgHandlersCreateBoundsOrganizationsPerOwner(t *testing.T) {
h, persistence := newOrgOwnershipLimitHandlers(t)
for i := 0; i < maxOwnedOrganizations; i++ {
if code := createOrgForTest(h, "alice", fmt.Sprintf("alice-%d", i)); code != http.StatusCreated {
t.Fatalf("organization %d: status %d, want 201", i, code)
}
}
req := withUser(httptest.NewRequest(http.MethodPost, "/api/orgs", bytes.NewBufferString(`{"id":"alice-over","displayName":"Over"}`)), "alice")
rec := httptest.NewRecorder()
h.HandleCreateOrg(rec, req)
if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "organization_limit_reached") {
t.Fatalf("organization past the limit: %d %s, want 409 organization_limit_reached", rec.Code, rec.Body.String())
}
if persistence.OrgExists("alice-over") {
t.Fatal("the refused organization was saved")
}
if code := createOrgForTest(h, "bob", "bob-0"); code != http.StatusCreated {
t.Fatalf("another user's first organization: status %d, want 201", code)
}
deleteReq := withUser(httptest.NewRequest(http.MethodDelete, "/api/orgs/alice-0", nil), "alice")
deleteReq.SetPathValue("id", "alice-0")
deleteRec := httptest.NewRecorder()
h.HandleDeleteOrg(deleteRec, deleteReq)
if deleteRec.Code != http.StatusNoContent {
t.Fatalf("delete: status %d: %s", deleteRec.Code, deleteRec.Body.String())
}
if code := createOrgForTest(h, "alice", "alice-again"); code != http.StatusCreated {
t.Fatalf("organization after deleting one: status %d, want 201", code)
}
for i := 0; i <= maxOwnedOrganizations; i++ {
if code := createOrgForTest(h, "root", fmt.Sprintf("root-%d", i)); code != http.StatusCreated {
t.Fatalf("administrator's organization %d: status %d, want 201", i, code)
}
}
}
func TestOrgHandlersCreateBoundsOrganizationsWithoutAccessPolicy(t *testing.T) {
t.Setenv("PULSE_DEV", "true")
previous := IsMultiTenantEnabled()
SetMultiTenantEnabled(true)
t.Cleanup(func() { SetMultiTenantEnabled(previous) })
persistence := config.NewMultiTenantPersistence(t.TempDir())
h := NewOrgHandlers(persistence, nil)
for i := 0; i < maxOwnedOrganizations; i++ {
if code := createOrgForTest(h, "alice", fmt.Sprintf("alice-%d", i)); code != http.StatusCreated {
t.Fatalf("organization %d: status %d, want 201", i, code)
}
}
if code := createOrgForTest(h, "alice", "alice-over"); code != http.StatusConflict {
t.Fatalf("organization past the limit: status %d, want 409", code)
}
if owned := ownedOrganizationsForTest(t, persistence, "alice"); owned != maxOwnedOrganizations {
t.Fatalf("alice owns %d organizations, want %d", owned, maxOwnedOrganizations)
}
}
func TestOrgHandlersCreateBoundsParallelRequests(t *testing.T) {
h, persistence := newOrgOwnershipLimitHandlers(t)
var wg sync.WaitGroup
for i := 0; i < maxOwnedOrganizations*2; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
createOrgForTest(h, "alice", fmt.Sprintf("alice-%d", i))
}(i)
}
wg.Wait()
if owned := ownedOrganizationsForTest(t, persistence, "alice"); owned != maxOwnedOrganizations {
t.Fatalf("alice owns %d organizations, want %d", owned, maxOwnedOrganizations)
}
}
func TestOrgHandlersOwnershipTransferCountsAgainstNewOwner(t *testing.T) {
h, persistence := newOrgOwnershipLimitHandlers(t)
for i := 0; i < maxOwnedOrganizations; i++ {
if code := createOrgForTest(h, "bob", fmt.Sprintf("bob-%d", i)); code != http.StatusCreated {
t.Fatalf("bob's organization %d: status %d, want 201", i, code)
}
}
for _, creator := range []string{"alice", "root"} {
orgID := creator + "-org"
if code := createOrgForTest(h, creator, orgID); code != http.StatusCreated {
t.Fatalf("%s: status %d, want 201", orgID, code)
}
inviteMemberForTest(t, h, orgID, creator, "bob", "admin", http.StatusAccepted)
acceptInvitationForTest(t, h, orgID, "bob")
}
rec := transferOrgForTest(h, "alice-org", "alice", "bob")
if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "organization_limit_reached") {
t.Fatalf("transfer to an owner at the limit: %d %s, want 409 organization_limit_reached", rec.Code, rec.Body.String())
}
org, err := persistence.LoadOrganization("alice-org")
if err != nil || org.OwnerUserID != "alice" || org.GetMemberRole("bob") != models.OrgRoleAdmin {
t.Fatalf("refused transfer changed the organization: %+v, %v", org, err)
}
if rec := transferOrgForTest(h, "root-org", "root", "bob"); rec.Code != http.StatusOK {
t.Fatalf("administrator's transfer: status %d, want 200: %s", rec.Code, rec.Body.String())
}
inviteMemberForTest(t, h, "alice-org", "alice", "carol", "viewer", http.StatusAccepted)
acceptInvitationForTest(t, h, "alice-org", "carol")
if rec := transferOrgForTest(h, "alice-org", "alice", "carol"); rec.Code != http.StatusOK {
t.Fatalf("transfer below the limit: status %d, want 200: %s", rec.Code, rec.Body.String())
}
}
+5
View File
@@ -351,6 +351,11 @@ func (b *patrolActionBroker) submit(ctx context.Context, proposal aicontracts.Ac
if proposal.InvestigationID == "" {
return aicontracts.ActionDisposition{}, fmt.Errorf("action proposal requires an investigation id")
}
// As in Capabilities: executors plan and dispatch for the organization in
// the context, so bind the broker's own before the lifecycle sees it.
if b.orgID != "" {
ctx = context.WithValue(ctx, OrgIDContextKey, b.orgID)
}
proposal = b.withProposalNote(ctx, proposal)
policyFactors, planningAutoAuthorized := b.planPolicyFactors(ctx, proposal, b.currentTime())
+42
View File
@@ -441,6 +441,48 @@ func TestPatrolActionBrokerCapabilitiesCatalog(t *testing.T) {
}
}
// availabilityOrgExecutor records the organization each availability check
// was asked about.
type availabilityOrgExecutor struct {
stubActionExecutor
orgs []string
}
func (e *availabilityOrgExecutor) CheckActionAvailable(ctx context.Context, _ unified.ActionRequest, _ unified.Resource) unified.ResourceActionReadiness {
e.orgs = append(e.orgs, GetOrgID(ctx))
return unified.ResourceActionReadiness{}
}
// An investigation's context names no organization, which executors read as
// the default one. The broker is bound to a tenant, so a proposal must be
// planned against that tenant's agents.
func TestPatrolActionBrokerSubmitPlansForTheBrokersOrganization(t *testing.T) {
h, _ := newPatrolBrokerTestHandlers(t, unified.ApprovalAdmin)
registry, err := h.buildRegistry("default")
if err != nil {
t.Fatal(err)
}
vm, ok := registry.Get("vm:42")
if !ok {
t.Fatal("seeded VM missing")
}
h.SetTenantStateProvider(assistantTenantSeedProvider{orgID: "acme", snapshot: models.StateSnapshot{LastUpdate: time.Now().UTC()}, vm: *vm})
executor := &availabilityOrgExecutor{}
h.SetActionExecutor(executor)
if _, err := NewPatrolActionBroker("acme", h).Submit(context.Background(), patrolTestProposal()); err != nil {
t.Fatalf("Submit: %v", err)
}
if len(executor.orgs) == 0 {
t.Fatal("planning did not check availability")
}
for _, orgID := range executor.orgs {
if orgID != "acme" {
t.Fatalf("availability checked in organizations %q, want only acme", executor.orgs)
}
}
}
func TestPatrolActionBrokerOptionalResourceScopeStillAuthorizesEligibleCapability(t *testing.T) {
h, executor := newPatrolBrokerTestHandlers(t, unified.ApprovalAdmin)
store, err := h.getStore("default")
+1 -1
View File
@@ -56,7 +56,7 @@ func (h *ProfileSuggestionHandler) HandleSuggestProfile(w http.ResponseWriter, r
// Parse request
var req SuggestionRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64*1024)).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
+16 -2
View File
@@ -72,6 +72,13 @@ func (h *HostedSignupHandlers) HandlePublicSignup(w http.ResponseWriter, r *http
http.NotFound(w, r)
return
}
// A runtime the control plane provisioned for one workspace already has its
// organization, owner and signed entitlement from there. Signup belongs to
// the control plane, so the runtime offers none of its own.
if hostedRuntimeHomeOrgID() != "" {
http.NotFound(w, r)
return
}
if h.persistence == nil {
writeErrorResponse(w, http.StatusServiceUnavailable, "orgs_unavailable", "Organization persistence is not configured", nil)
return
@@ -144,17 +151,24 @@ func (h *HostedSignupHandlers) HandlePublicSignup(w http.ResponseWriter, r *http
ownerEmail = strings.ToLower(strings.TrimSpace(req.Email))
}
// An organization the provisioner found rather than created is not this
// request's to initialize or to undo: it keeps its billing state, and a
// later failure must not delete it.
created := result.Status == hosted.ProvisionStatusCreated
var cleanupOnce sync.Once
cleanupProvisioning := func() {
cleanupOnce.Do(func() {
hosted.GetHostedMetrics().RecordProvisionStatus(hosted.ProvisionMetricStatusFailure)
provisioner.RollbackProvisioning(orgID)
if created {
provisioner.RollbackProvisioning(orgID)
}
})
}
// Seed trial billing state so the tenant is usable immediately (before Stripe checkout completes).
// Stripe webhook will overwrite this with active subscription state on successful checkout.
if h.billingStore != nil {
if h.billingStore != nil && created {
now := time.Now().UTC()
trialState := buildTrialBillingStateWithPlanFromLicensing(
now,
@@ -0,0 +1,135 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
authpkg "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
)
// An organization manager may pair a phone, but the relay mobile scope stands
// in for the action scopes, so the token must not carry action authority its
// minter's own session does not have.
func TestRelayMobileTokenCarriesNoMoreActionAuthorityThanItsMinter(t *testing.T) {
defer SetMultiTenantEnabled(false)
SetMultiTenantEnabled(true)
t.Setenv("PULSE_DEV", "true")
dataDir := t.TempDir()
hashed, err := authpkg.HashPassword("Password!1")
if err != nil {
t.Fatalf("hash password: %v", err)
}
cfg := &config.Config{
DataPath: dataDir,
ConfigPath: dataDir,
AuthUser: "platform-admin",
AuthPass: hashed,
}
org := &models.Organization{
ID: "org-a",
DisplayName: "Org A",
OwnerUserID: "org-owner",
Members: []models.OrganizationMember{
{UserID: "org-owner", Role: models.OrgRoleOwner, AddedAt: time.Now()},
},
}
if err := config.NewMultiTenantPersistence(dataDir).SaveOrganization(org); err != nil {
t.Fatalf("save organization: %v", err)
}
router := newMultiTenantRouter(t, cfg)
setLicenseTierForHandlersForTests(t, router.licenseHandlers, "org-a", pkglicensing.TierRelay)
setLicenseTierForHandlersForTests(t, router.licenseHandlers, "default", pkglicensing.TierRelay)
mint := func(t *testing.T, user, orgID string) (string, config.APITokenRecord) {
t.Helper()
sessionToken := "relay-mobile-" + user + "-" + strings.ReplaceAll(time.Now().UTC().Format(time.RFC3339Nano), ":", "-")
GetSessionStore().CreateSession(sessionToken, time.Hour, "agent", "127.0.0.1", user)
req := httptest.NewRequest(http.MethodPost, "/api/security/tokens/relay-mobile", strings.NewReader(`{}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CSRF-Token", generateCSRFToken(sessionToken))
req.Header.Set("X-Pulse-Org-ID", orgID)
req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: sessionToken})
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("mint as %s: status = %d, want %d: %s", user, rec.Code, http.StatusOK, rec.Body.String())
}
var payload struct {
Token string `json:"token"`
Record apiTokenDTO `json:"record"`
}
if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {
t.Fatalf("decode mint response: %v", err)
}
config.Mu.RLock()
defer config.Mu.RUnlock()
for _, stored := range cfg.APITokens {
if stored.ID == payload.Record.ID {
return payload.Token, stored.Clone()
}
}
t.Fatalf("minted token %s is not stored", payload.Record.ID)
return "", config.APITokenRecord{}
}
request := func(rawToken, orgID, method, path string) int {
req := httptest.NewRequest(method, path, strings.NewReader(`{}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", rawToken)
req.Header.Set("X-Pulse-Org-ID", orgID)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
return rec.Code
}
actionRoutes := []struct{ method, path string }{
{http.MethodGet, "/api/actions"},
{http.MethodGet, "/api/actions/pending"},
{http.MethodGet, "/api/actions/action-1"},
{http.MethodPost, "/api/actions/action-1/decision"},
{http.MethodPost, "/api/actions/action-1/execute"},
{http.MethodGet, "/api/ai/approvals"},
{http.MethodPost, "/api/ai/approvals/approval-1/approve"},
{http.MethodPost, "/api/ai/approvals/approval-1/deny"},
}
managerToken, managerRecord := mint(t, "org-owner", "org-a")
if !tokenActionsWithheld(&managerRecord) {
t.Fatalf("organization manager's mobile token is not marked: %v", managerRecord.Metadata)
}
for _, capability := range []string{authpkg.ActionPlan, authpkg.ActionApprove, authpkg.ActionExecute} {
if tokenHasActionCapabilityScope(&managerRecord, capability) {
t.Fatalf("organization manager's mobile token grants the %s capability", capability)
}
}
for _, route := range actionRoutes {
if code := request(managerToken, "org-a", route.method, route.path); code != http.StatusForbidden {
t.Fatalf("organization manager's mobile token on %s %s = %d, want %d", route.method, route.path, code, http.StatusForbidden)
}
}
// The rest of the mobile surface stays with the paired phone.
if code := request(managerToken, "org-a", http.MethodGet, "/api/ai/patrol/attention"); code == http.StatusForbidden || code == http.StatusUnauthorized {
t.Fatalf("organization manager's mobile token on GET /api/ai/patrol/attention = %d, want it admitted", code)
}
adminToken, adminRecord := mint(t, "platform-admin", "default")
if tokenActionsWithheld(&adminRecord) {
t.Fatalf("administrator's mobile token is marked: %v", adminRecord.Metadata)
}
if !tokenHasActionCapabilityScope(&adminRecord, authpkg.ActionApprove) || !tokenHasActionCapabilityScope(&adminRecord, authpkg.ActionExecute) {
t.Fatal("administrator's mobile token lost its action capability")
}
for _, route := range actionRoutes {
if code := request(adminToken, "default", route.method, route.path); code == http.StatusForbidden || code == http.StatusUnauthorized {
t.Fatalf("administrator's mobile token on %s %s = %d, want it admitted", route.method, route.path, code)
}
}
}
+145
View File
@@ -0,0 +1,145 @@
package api
import (
"context"
"errors"
"io"
"net/http"
"sync"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
)
type requestBodyAuthorityKey struct{}
// errRequestAuthorityWithdrawn is deliberately not io.EOF: a body that outlived
// its credential is neither a complete document nor an omitted one.
var errRequestAuthorityWithdrawn = errors.New("credential withdrawn before the request body arrived")
// requestBodyAuthority binds a request body to the credential that admitted
// its headers. Authentication runs when the headers arrive, but the server
// reads the body with no deadline: a client can hold back the last byte until
// its session has been logged out or its API token deleted, and still have
// the request carried out. Every body read therefore rechecks the admitted
// credential, and once it is withdrawn the handler receives no further input.
type requestBodyAuthority struct {
mu sync.Mutex
allowed func() bool
withdrawn bool
}
// withRequestBodyAuthority lets the outermost response writer share a body's
// authority, so a withdrawn credential gets the same generic 401 as a
// withheld protected read, whatever the handler makes of its failed read.
// Bodyless requests cannot be held open.
func withRequestBodyAuthority(r *http.Request) (*http.Request, *requestBodyAuthority) {
if r.Body == nil || r.Body == http.NoBody {
return r, nil
}
authority := &requestBodyAuthority{}
return r.WithContext(context.WithValue(r.Context(), requestBodyAuthorityKey{}, authority)), authority
}
// retainRequestBodyAuthority runs at credential admission and retains only
// the validity of the credential selected there: the exact local session, or
// the API token's live identity. It does not extend expiry or rerun
// authentication. A scope or organization edit leaves a token valid and stays
// the route's decision (403), and proxy, Basic and bypass admission stay with
// the route as they do for protected reads.
func retainRequestBodyAuthority(cfg *config.Config, r *http.Request) {
if r.Body == nil || r.Body == http.NoBody {
return
}
allowed := admittedTokenRevalidator(cfg, r)
if allowed == nil {
allowed = sessionReadRevalidator(r)
}
authority, _ := r.Context().Value(requestBodyAuthorityKey{}).(*requestBodyAuthority)
if authority == nil {
if allowed == nil {
return
}
// Not every caller runs inside ErrorHandler. The body is still bound;
// only the handler's own answer to the failed read is left as it is.
authority = &requestBodyAuthority{}
*r = *r.WithContext(context.WithValue(r.Context(), requestBodyAuthorityKey{}, authority))
}
// Only the credential selected by the latest admission owns the body. A
// later proxy or Basic admission must not inherit an earlier one's check.
authority.admit(allowed)
if allowed == nil {
return
}
// Middleware may authenticate a request more than once.
if _, bound := r.Body.(*authorityBoundBody); !bound {
r.Body = &authorityBoundBody{ReadCloser: r.Body, authority: authority}
}
}
// admittedTokenRevalidator reports whether the admitted API token is still the
// same live credential in the inventory that issued it. It updates no token
// metadata and never falls back to another inventory once a tenant owner is
// withdrawn.
func admittedTokenRevalidator(cfg *config.Config, req *http.Request) func() bool {
admitted := getAPITokenRecordFromRequest(req)
if admitted == nil {
return nil
}
source, tenantInventory := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource)
tenantInventory = tenantInventory && source.orgID != "" && source.orgID != "default"
return func() bool {
config.Mu.RLock()
defer config.Mu.RUnlock()
live := cfg
if tenantInventory {
live = tenantTokenConfigForRequest(req)
}
return live != nil && admittedTokenLocked(live, admitted) != nil
}
}
func (a *requestBodyAuthority) admit(allowed func() bool) {
a.mu.Lock()
defer a.mu.Unlock()
// Withdrawal is final for this request, whatever is admitted afterwards.
if !a.withdrawn {
a.allowed = allowed
}
}
func (a *requestBodyAuthority) permit() bool {
a.mu.Lock()
defer a.mu.Unlock()
if !a.withdrawn && a.allowed != nil && !a.allowed() {
a.withdrawn = true
}
return !a.withdrawn
}
// refused reports whether a body read has found the admitted credential
// withdrawn. It never rechecks: a response is withheld only from a request
// that was denied its input, not from one that completed and then logged out.
func (a *requestBodyAuthority) refused() bool {
if a == nil {
return false
}
a.mu.Lock()
defer a.mu.Unlock()
return a.withdrawn
}
// authorityBoundBody deliberately exposes no Unwrap or WriterTo escape around
// the check. Bytes are checked as they arrive, not only at EOF: a JSON decoder
// can finish a document without ever reaching the end of the body.
type authorityBoundBody struct {
io.ReadCloser
authority *requestBodyAuthority
}
func (b *authorityBoundBody) Read(p []byte) (int, error) {
n, err := b.ReadCloser.Read(p)
if (n > 0 || err == io.EOF) && !b.authority.permit() {
return 0, errRequestAuthorityWithdrawn
}
return n, err
}
+206
View File
@@ -0,0 +1,206 @@
package api
import (
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
)
const (
parkedBodySession = "synthetic-parked-body-session"
parkedBodyToken = "synthetic-parked-body-token.12345678"
)
// Authentication sees only the request headers. A client can send them while
// its credential is valid, hold back the end of the body and complete the
// request after logout, a password change, token deletion or expiry. The real
// routes must answer as they would for that withdrawn credential and must not
// issue or save anything.
func TestParkedRequestBodyFollowsCredentialWithdrawal(t *testing.T) {
t.Setenv("ALLOW_ADMIN_BYPASS", "")
resetAdminBypassState()
t.Cleanup(resetAdminBypassState)
routes := map[string]struct{ path, body string }{
"session": {"/api/security/tokens", `{"name":"parked","scopes":["*"]}`},
"token": {"/api/agent-install-command", `{"type":"host","enableCommands":true}`},
}
for _, test := range []struct {
credential, change string
want int
}{
{"session", "none", http.StatusOK},
{"session", "invalidated", http.StatusUnauthorized},
{"session", "expired", http.StatusUnauthorized},
{"session", "principal", http.StatusUnauthorized},
{"session", "replaced", http.StatusUnauthorized},
{"token", "none", http.StatusOK},
{"token", "revoked", http.StatusUnauthorized},
{"token", "rotated", http.StatusUnauthorized},
{"token", "expired", http.StatusUnauthorized},
{"token", "owner changed", http.StatusUnauthorized},
// A still-valid token's lost privilege is the route's 403, not a 401.
{"token", "unrelated scope removed", http.StatusOK},
} {
t.Run(test.credential+"/"+test.change, func(t *testing.T) {
InitSessionStore(t.TempDir())
caller := newTokenRecord(t, parkedBodyToken, []string{config.ScopeSettingsWrite, config.ScopeAgentExec, config.ScopeMonitoringRead}, nil)
caller.ID, caller.OrgID = "fixture-parked-caller", "default"
cfg := newTestConfigWithTokens(t, caller)
cfg.AuthUser, cfg.AuthPass = "admin", "$2a$10$synthetic.parked.body.password.hash.fixture.value.0000"
router := newTestRouter(t, cfg, nil, nil, nil, nil, "test")
route := routes[test.credential]
paused := &tokenWithdrawalBody{Reader: strings.NewReader(route.body), started: make(chan struct{}), resume: make(chan struct{})}
req := httptest.NewRequest(http.MethodPost, route.path, paused)
req.Header.Set("Content-Type", "application/json")
if test.credential == "session" {
GetSessionStore().CreateSession(parkedBodySession, time.Hour, "fixture", "192.0.2.10", "admin")
req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: parkedBodySession})
req.Header.Set("X-CSRF-Token", generateCSRFToken(parkedBodySession))
} else {
req.Header.Set("X-API-Token", parkedBodyToken)
}
rec := httptest.NewRecorder()
done := make(chan struct{})
go func() { defer close(done); router.Handler().ServeHTTP(rec, req) }()
released := false
defer func() {
if !released {
close(paused.resume)
}
<-done
}()
select {
case <-paused.started:
case <-done:
t.Fatalf("request was refused before its body was read: status=%d body=%s", rec.Code, rec.Body.String())
case <-time.After(5 * time.Second):
t.Fatal("registered route did not reach its body reader")
}
if test.credential == "session" && test.change != "none" {
mutateReadSession(parkedBodySession, test.change)
}
config.Mu.Lock()
for i := range cfg.APITokens {
if test.credential != "token" || cfg.APITokens[i].ID != caller.ID {
continue
}
switch test.change {
case "rotated":
cfg.APITokens[i].Hash = "different-credential-hash"
case "expired":
expires := time.Now().Add(-time.Second)
cfg.APITokens[i].ExpiresAt = &expires
case "owner changed":
cfg.APITokens[i].Metadata = map[string]string{apiTokenMetadataOwnerUserID: "different-owner"}
case "unrelated scope removed":
cfg.APITokens[i].Scopes = []string{config.ScopeSettingsWrite, config.ScopeAgentExec}
}
}
if test.change == "revoked" {
cfg.RemoveAPIToken(caller.ID)
}
config.Mu.Unlock()
before := tokenWithdrawalInventory(t, router)
close(paused.resume)
released = true
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("request did not finish after its body resumed")
}
if rec.Code != test.want {
t.Fatalf("parked request status=%d, want %d: %s", rec.Code, test.want, rec.Body.String())
}
issued := strings.Contains(rec.Body.String(), `"token":`)
changed := string(tokenWithdrawalInventory(t, router)) != string(before)
if test.want == http.StatusOK {
if !issued || !changed {
t.Error("a request whose credential stayed valid was not carried out")
}
return
}
// The same generic answer as a withheld protected read, not the
// handler's "invalid body" and never a structured success.
if rec.Body.String() != "Authentication required\n" || strings.Contains(rec.Header().Get("Content-Type"), "json") {
t.Errorf("withdrawn credential was answered %q", rec.Body.String())
}
if issued {
t.Error("withdrawn credential received a new credential")
}
if changed {
t.Error("withdrawn credential changed the live inventory")
}
})
}
}
// The withdrawal must reach a handler as a failed read, never as the end of a
// complete or omitted body, and only for the credential that admitted it.
func TestRequestBodyAuthorityAdmission(t *testing.T) {
InitSessionStore(t.TempDir())
GetSessionStore().CreateSession(parkedBodySession, time.Hour, "fixture", "192.0.2.10", "operator")
cfg := newTestConfigWithTokens(t, newTokenRecord(t, parkedBodyToken, []string{config.ScopeWildcard}, nil))
newRequest := func(body io.Reader) *http.Request {
req := httptest.NewRequest(http.MethodPost, "http://192.0.2.1/api/security/tokens", body)
req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: parkedBodySession})
return req
}
// Bodyless requests cannot be held open and carry no check.
bodyless := newRequest(nil)
if !CheckAuth(cfg, httptest.NewRecorder(), bodyless) || bodyless.Body != http.NoBody {
t.Fatal("bodyless request was bound")
}
req := newRequest(strings.NewReader(`{"name":"parked"}`))
if !CheckAuth(cfg, httptest.NewRecorder(), req) || !CheckAuth(cfg, httptest.NewRecorder(), req) {
t.Fatal("session admission failed")
}
bound, ok := req.Body.(*authorityBoundBody)
if !ok {
t.Fatal("admitted body was not bound to its session")
}
if _, nested := bound.ReadCloser.(*authorityBoundBody); nested {
t.Fatal("repeated admission nested the body check")
}
first := make([]byte, 4)
if n, err := req.Body.Read(first); n != len(first) || err != nil {
t.Fatalf("valid session read n=%d err=%v", n, err)
}
// An explicit token now owns the request; the session no longer decides.
req.Header.Set("X-API-Token", parkedBodyToken)
if !CheckAuth(cfg, httptest.NewRecorder(), req) {
t.Fatal("token admission failed")
}
GetSessionStore().InvalidateSession(parkedBodySession)
if n, err := req.Body.Read(first); n != len(first) || err != nil {
t.Fatalf("token-owned body followed the unselected session: n=%d err=%v", n, err)
}
config.Mu.Lock()
cfg.APITokens = nil
config.Mu.Unlock()
rest, err := io.ReadAll(req.Body)
if len(rest) != 0 || !errors.Is(err, errRequestAuthorityWithdrawn) || errors.Is(err, io.EOF) {
t.Fatalf("withdrawn token read %q, err=%v", rest, err)
}
// Withdrawal is final, whatever this request is admitted with afterwards.
config.Mu.Lock()
cfg.APITokens = []config.APITokenRecord{newTokenRecord(t, parkedBodyToken, []string{config.ScopeWildcard}, nil)}
config.Mu.Unlock()
if !CheckAuth(cfg, httptest.NewRecorder(), req) {
t.Fatal("reissued token admission failed")
}
if _, err := req.Body.Read(first); !errors.Is(err, errRequestAuthorityWithdrawn) {
t.Fatalf("withdrawn request resumed reading its body: %v", err)
}
}
+8 -3
View File
@@ -773,6 +773,11 @@ func (h *QueryService) HandleStats(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(stats)
}
// maxResourceMutationRequestBytes bounds the link, unlink and report-merge
// bodies, which carry resource identifiers and a short operator note that is
// persisted.
const maxResourceMutationRequestBytes = 64 << 10
// HandleLink handles POST /api/resources/{id}/link.
func (h *QueryService) HandleLink(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -800,7 +805,7 @@ func (h *QueryService) HandleLink(w http.ResponseWriter, r *http.Request) {
TargetID string `json:"targetId"`
Reason string `json:"reason"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxResourceMutationRequestBytes)).Decode(&payload); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
@@ -859,7 +864,7 @@ func (h *QueryService) HandleUnlink(w http.ResponseWriter, r *http.Request) {
TargetID string `json:"targetId"`
Reason string `json:"reason"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxResourceMutationRequestBytes)).Decode(&payload); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
@@ -917,7 +922,7 @@ func (h *QueryService) HandleReportMerge(w http.ResponseWriter, r *http.Request)
Sources []string `json:"sources"`
Notes string `json:"notes"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil && !errors.Is(err, io.EOF) {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxResourceMutationRequestBytes)).Decode(&payload); err != nil && !errors.Is(err, io.EOF) {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
@@ -1796,6 +1796,33 @@ func TestResourceLinkMergesResources(t *testing.T) {
}
}
func TestResourceMutationsRejectOversizedBody(t *testing.T) {
h := NewQueryService(&config.Config{DataPath: t.TempDir()})
h.SetStateProvider(resourceStateProvider{})
padding := strings.Repeat("a", maxResourceMutationRequestBytes)
cases := []struct {
action string
handler http.HandlerFunc
payload map[string]any
}{
{"link", h.HandleLink, map[string]any{"targetId": "agent:beta", "reason": padding}},
{"unlink", h.HandleUnlink, map[string]any{"targetId": "agent:beta", "reason": padding}},
{"report-merge", h.HandleReportMerge, map[string]any{"sources": []string{"agent"}, "notes": padding}},
}
for _, tc := range cases {
t.Run(tc.action, func(t *testing.T) {
body, _ := json.Marshal(tc.payload)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/resources/agent:alpha/"+tc.action, bytes.NewReader(body))
tc.handler(rec, req)
if rec.Code != http.StatusBadRequest || strings.TrimSpace(rec.Body.String()) != "Invalid JSON" {
t.Fatalf("%s status = %d body=%q, want 400 Invalid JSON", tc.action, rec.Code, rec.Body.String())
}
})
}
}
func TestResourceLinkFromAgentKeepsHypervisorGuestAuthorityInAPIState(t *testing.T) {
now := time.Now().UTC()
tests := []struct {
+12 -2
View File
@@ -26,7 +26,7 @@ type ResourceHandlers struct {
tenantStateProvider TenantStateProvider
actionExecutor ActionExecutor
broadcastAvailability atomic.Pointer[broadcastAvailabilityChecker]
actionCompleted func(unified.ActionAuditRecord)
actionCompleted func(orgID string, record unified.ActionAuditRecord)
actionTransition func(orgID string, record unified.ActionAuditRecord)
policyAdmission *actionlifecycle.PolicyAdmissionCoordinator
actionEmergencyStop func(orgID string) (bool, error)
@@ -35,6 +35,7 @@ type ResourceHandlers struct {
actionLiveCheckAuthorizer actionlifecycle.LiveCheckAuthorizer
actionRefreshPlanner actionlifecycle.RefreshPlanner
operatorStateChanged func(orgID, resourceID string)
operatorStateRemediation func(*http.Request) bool
}
type SupplementalRecordsProvider = resourceapi.SupplementalRecordsProvider
@@ -119,7 +120,7 @@ func (h *ResourceHandlers) SetActionRefreshPlanner(planner actionlifecycle.Refre
h.actionRefreshPlanner = planner
}
func (h *ResourceHandlers) SetActionCompletedPublisher(publisher func(unified.ActionAuditRecord)) {
func (h *ResourceHandlers) SetActionCompletedPublisher(publisher func(orgID string, record unified.ActionAuditRecord)) {
h.actionCompleted = publisher
}
@@ -131,6 +132,15 @@ func (h *ResourceHandlers) SetOperatorStateChanged(callback func(orgID, resource
h.operatorStateChanged = callback
}
// SetOperatorStateRemediationAuthority sets who may change what a resource's
// operator state tells the action lifecycle and Patrol: the Never
// auto-remediate lock, the lifecycle state and the automatic remediation
// policy. Without it nobody may. Everyone the route admits keeps the rest of
// the record (monitoring mode, maintenance windows, criticality, notes).
func (h *ResourceHandlers) SetOperatorStateRemediationAuthority(allowed func(*http.Request) bool) {
h.operatorStateRemediation = allowed
}
func (h *ResourceHandlers) buildRegistry(orgID string) (*unified.ResourceRegistry, error) {
return h.ensureQueryService().BuildRegistry(orgID)
}
+71 -1
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"net/http"
"reflect"
"strings"
"time"
@@ -38,6 +39,12 @@ type resourceOperatorStateAPI struct {
SetBy string `json:"setBy,omitempty"`
}
// maxOperatorStateRequestBytes bounds the PUT body like the neighbouring
// action decision routes. The record is a handful of enums, timestamps and
// short free-text fields; the decoder buffers the whole document and the
// note is persisted, so the body must be bounded before it is decoded.
const maxOperatorStateRequestBytes = 64 << 10
// resourceOperatorStateLookupAPI is the UI-safe read envelope. The canonical
// agent/API contract keeps a missing explicit record as 404 so callers can
// branch on operator_state_not_set. Interactive clients use view=lookup to
@@ -94,6 +101,10 @@ func toResourceOperatorStateAPI(state unified.ResourceOperatorState) resourceOpe
// audit attribution honest.
// - DELETE clears the entry, idempotent. Returns 204 whether or not
// an entry was present.
// - PUT and DELETE return 403 when they would change the remediation
// lock, lifecycle state or automatic remediation policy and the
// request lacks the authority set by
// SetOperatorStateRemediationAuthority.
func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, r *http.Request) {
resourceID := extractOperatorStateResourceID(r.URL.Path)
if resourceID == "" {
@@ -134,7 +145,7 @@ func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, r
case http.MethodPut:
var payload resourceOperatorStateAPI
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxOperatorStateRequestBytes)).Decode(&payload); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
@@ -159,13 +170,23 @@ func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, r
SetAt: time.Now().UTC(),
SetBy: getUserID(r),
}
mayChangeRemediation := h.operatorStateRemediation != nil && h.operatorStateRemediation(r)
var persisted unified.ResourceOperatorState
err := h.ActionLifecycle().WithPolicyMutation(func() error {
if !mayChangeRemediation {
if err := refuseOperatorStateRemediationChange(store, state); err != nil {
return err
}
}
var writeErr error
persisted, writeErr = unified.SetResourceOperatorStateWithMaintenanceLifecycle(store, state)
return writeErr
})
if err != nil {
if errors.Is(err, errOperatorStateRemediationAuthority) {
http.Error(w, operatorStateRemediationDenied, http.StatusForbidden)
return
}
if errors.Is(err, unified.ErrResourceOperatorStateInvalid) {
writeJSONError(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeOperatorStateInvalid, err.Error())
return
@@ -181,9 +202,20 @@ func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, r
case http.MethodDelete:
observedAt := time.Now().UTC()
actor := getUserID(r)
mayChangeRemediation := h.operatorStateRemediation != nil && h.operatorStateRemediation(r)
if err := h.ActionLifecycle().WithPolicyMutation(func() error {
if !mayChangeRemediation {
// Clearing the record restores the default remediation policy.
if err := refuseOperatorStateRemediationChange(store, unified.ResourceOperatorState{CanonicalID: resourceID}); err != nil {
return err
}
}
return unified.ClearResourceOperatorStateWithMaintenanceLifecycle(store, resourceID, observedAt, actor)
}); err != nil {
if errors.Is(err, errOperatorStateRemediationAuthority) {
http.Error(w, operatorStateRemediationDenied, http.StatusForbidden)
return
}
http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
return
}
@@ -197,6 +229,44 @@ func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, r
}
}
var errOperatorStateRemediationAuthority = errors.New("operator state remediation policy requires action review authority")
// Only sessions are refused (tokens hold the authority by scope), so this is
// not an agent-surface error code.
const operatorStateRemediationDenied = "Administrator privileges or an explicit action grant are required to change the remediation lock, lifecycle or automatic remediation policy"
// refuseOperatorStateRemediationChange returns
// errOperatorStateRemediationAuthority when the write would change the
// remediation policy the action lifecycle and Patrol obey, for a request that
// may not (SetOperatorStateRemediationAuthority). A policy already saved adds
// no authority, so anyone the route admits round-trips what an administrator
// set while saving a maintenance window or a note. It must run inside
// WithPolicyMutation: the record it compares is then the one the write
// replaces, and a lock saved concurrently is refused instead of overwritten.
func refuseOperatorStateRemediationChange(store unified.ResourceStore, requested unified.ResourceOperatorState) error {
// A missing record reads as the zero state, which is the default policy.
saved, _, err := store.GetResourceOperatorState(requested.CanonicalID)
if err != nil {
return err
}
if operatorStateRemediationPolicyChanged(saved, requested) {
return errOperatorStateRemediationAuthority
}
return nil
}
// operatorStateRemediationPolicyChanged reports whether two records differ in
// the fields BlocksRemediation and AllowsAutoRemediationAt read: the Never
// auto-remediate lock, the lifecycle state (Retired blocks remediation too)
// and the automatic remediation policy.
func operatorStateRemediationPolicyChanged(saved, requested unified.ResourceOperatorState) bool {
saved = unified.NormalizeResourceOperatorState(saved)
requested = unified.NormalizeResourceOperatorState(requested)
return saved.NeverAutoRemediate != requested.NeverAutoRemediate ||
saved.LifecycleState != requested.LifecycleState ||
!reflect.DeepEqual(saved.AutoRemediationPolicy, requested.AutoRemediationPolicy)
}
// resolveOperatorStateCanonicalID ensures every UI and agent entry point writes
// one policy record even when it starts from a source-native alert ID, a
// superseded ID, or another canonical identity alias. If the live registry
+124 -1
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
@@ -28,7 +29,10 @@ func newOperatorStateHandlersWithDataDir(t *testing.T) (*ResourceHandlers, strin
t.Helper()
dataDir := t.TempDir()
cfg := &config.Config{DataPath: dataDir}
return NewResourceHandlers(cfg), dataDir
h := NewResourceHandlers(cfg)
// These fixtures call the handler as the router admits an administrator.
h.SetOperatorStateRemediationAuthority(func(*http.Request) bool { return true })
return h, dataDir
}
func dropOperatorStateTimelineTable(t *testing.T, dataDir string) {
@@ -410,6 +414,30 @@ func TestHandleResourceOperatorState_PutRejectsInvalidWith400(t *testing.T) {
}
}
func TestHandleResourceOperatorState_PutRejectsOversizedBody(t *testing.T) {
h := newOperatorStateHandlers(t)
// The decoder buffers the whole document and the note is persisted, so
// the body must be bounded before decode.
body, _ := json.Marshal(map[string]any{
"note": strings.Repeat("a", maxOperatorStateRequestBytes),
})
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPut, "/api/resources/vm:101/operator-state", bytes.NewReader(body))
h.HandleResourceOperatorState(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400 on oversized body; got %d", rec.Code)
}
getRec := httptest.NewRecorder()
getReq := httptest.NewRequest(http.MethodGet, "/api/resources/vm:101/operator-state", nil)
h.HandleResourceOperatorState(getRec, getReq)
if getRec.Code != http.StatusNotFound {
t.Errorf("oversized PUT must not persist; GET should still 404; got %d", getRec.Code)
}
}
func TestHandleResourceOperatorState_DeleteIsIdempotent(t *testing.T) {
h := newOperatorStateHandlers(t)
@@ -536,3 +564,98 @@ func TestMaintenanceAlertSubjectsReadAndWriteCanonicalOperatorState(t *testing.T
})
}
}
// Part of the operator-state record is the per-resource policy every approval
// and dispatch obeys. Token scopes do not bind sessions, so a signed-in viewer
// must hold the action review capability to change the remediation lock, the
// lifecycle state or the automatic remediation policy. The viewer keeps the
// rest of the record and round-trips the policy an administrator saved; reads
// stay open, and tokens keep the documented monitoring:write scope.
func TestOperatorStateRemediationPolicyRequiresActionReviewForProxySessions(t *testing.T) {
rawToken := "operator-state-write-authority.12345678"
cfg := newTestConfigWithTokens(t, newTokenRecord(t, rawToken,
[]string{config.ScopeMonitoringRead, config.ScopeMonitoringWrite}, nil))
cfg.ProxyAuthSecret = "fixture-proxy-secret"
cfg.ProxyAuthUserHeader = "X-Remote-User"
cfg.ProxyAuthRoleHeader = "X-Remote-Roles"
cfg.ProxyAuthAdminRole = "admin"
router := newTestRouter(t, cfg, nil, nil, nil, nil, "1.0.0")
cleanupTestRouter(t, router)
serve := func(method, resource, body string, headers map[string]string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, "/api/resources/"+resource+"/operator-state", bytes.NewBufferString(body))
for name, value := range headers {
req.Header.Set(name, value)
}
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
return rec
}
proxyUser := func(role string) map[string]string {
return map[string]string{"X-Proxy-Secret": cfg.ProxyAuthSecret, "X-Remote-User": "fixture-" + role, "X-Remote-Roles": role}
}
admin, viewer := proxyUser("admin"), proxyUser("viewer")
saved := func(resource string) resourceOperatorStateAPI {
t.Helper()
rec := serve(http.MethodGet, resource, "", viewer)
if rec.Code != http.StatusOK {
t.Fatalf("viewer GET %s: %d want 200: %s", resource, rec.Code, rec.Body.String())
}
var state resourceOperatorStateAPI
if err := json.Unmarshal(rec.Body.Bytes(), &state); err != nil {
t.Fatalf("decode state: %v", err)
}
return state
}
const locked = `{"neverAutoRemediate":true,"autoRemediationPolicy":{"enabled":true,"capabilityNames":["restart"]}}`
if rec := serve(http.MethodPut, "vm:101", locked, admin); rec.Code != http.StatusOK {
t.Fatalf("admin PUT: %d want 200: %s", rec.Code, rec.Body.String())
}
for name, write := range map[string]struct{ method, body string }{
"clear the record": {http.MethodDelete, ""},
"lift the lock": {http.MethodPut, `{"neverAutoRemediate":false,"autoRemediationPolicy":{"enabled":true,"capabilityNames":["restart"]}}`},
"widen the policy": {http.MethodPut, `{"neverAutoRemediate":true,"autoRemediationPolicy":{"enabled":true,"capabilityNames":["restart","stop"]}}`},
"drop the policy": {http.MethodPut, `{"neverAutoRemediate":true}`},
"retire the record": {http.MethodPut, `{"lifecycleState":"retired","neverAutoRemediate":true,"autoRemediationPolicy":{"enabled":true,"capabilityNames":["restart"]}}`},
} {
if rec := serve(write.method, "vm:101", write.body, viewer); rec.Code != http.StatusForbidden {
t.Fatalf("viewer %s: %d want 403: %s", name, rec.Code, rec.Body.String())
}
}
if state := saved("vm:101"); !state.NeverAutoRemediate || len(state.AutoRemediationPolicy.CapabilityNames) != 1 || state.SetBy != "fixture-admin" {
t.Fatalf("a refused viewer write changed the record: %+v", state)
}
// The viewer saves a note around the administrator's policy.
const lockedWithNote = `{"neverAutoRemediate":true,"autoRemediationPolicy":{"enabled":true,"capabilityNames":[" restart "]},"note":"checked"}`
if rec := serve(http.MethodPut, "vm:101", lockedWithNote, viewer); rec.Code != http.StatusOK {
t.Fatalf("viewer PUT preserving the policy: %d want 200: %s", rec.Code, rec.Body.String())
}
if state := saved("vm:101"); !state.NeverAutoRemediate || state.Note != "checked" {
t.Fatalf("viewer note around the lock: %+v", state)
}
// A resource with no record holds the default policy.
if rec := serve(http.MethodPut, "vm:102", `{"neverAutoRemediate":true}`, viewer); rec.Code != http.StatusForbidden {
t.Fatalf("viewer lock on an unset resource: %d want 403: %s", rec.Code, rec.Body.String())
}
if rec := serve(http.MethodPut, "vm:102", `{"monitoringMode":"muted","note":"lab"}`, viewer); rec.Code != http.StatusOK {
t.Fatalf("viewer monitoring mode on an unset resource: %d want 200: %s", rec.Code, rec.Body.String())
}
if rec := serve(http.MethodDelete, "vm:102", "", viewer); rec.Code != http.StatusNoContent {
t.Fatalf("viewer DELETE of a record with the default policy: %d want 204: %s", rec.Code, rec.Body.String())
}
token := map[string]string{"X-API-Token": rawToken}
if rec := serve(http.MethodPut, "vm:101", `{"neverAutoRemediate":false}`, token); rec.Code != http.StatusOK {
t.Fatalf("monitoring:write token PUT: %d want 200: %s", rec.Code, rec.Body.String())
}
if rec := serve(http.MethodPut, "vm:101", locked, admin); rec.Code != http.StatusOK {
t.Fatalf("admin PUT: %d want 200: %s", rec.Code, rec.Body.String())
}
if rec := serve(http.MethodDelete, "vm:101", "", admin); rec.Code != http.StatusNoContent {
t.Fatalf("admin DELETE: %d want 204: %s", rec.Code, rec.Body.String())
}
}
-2
View File
@@ -391,8 +391,6 @@ var publicRouteAllowlist = []string{
"/api/setup-script",
"/api/config/export",
"/api/config/import",
"/api/system/verify-temperature-ssh",
"/api/system/ssh-config",
"/api/auto-register",
"/api/auto-unregister",
"/auth/cloud-handoff",
+242 -165
View File
@@ -17,6 +17,7 @@ import (
"path"
"path/filepath"
"runtime"
"slices"
"sort"
"strconv"
"strings"
@@ -60,7 +61,6 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/websocket"
"github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
"github.com/rcourtman/pulse-go-rewrite/pkg/diskinventory"
"github.com/rcourtman/pulse-go-rewrite/pkg/extensions"
metricstore "github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
@@ -164,6 +164,7 @@ type Router struct {
checksumCache map[string]checksumCacheEntry
unifiedAgentValidationCache sync.Map
installScriptClient *http.Client
proxiedReleaseAssets proxiedReleaseAssets
relayMu sync.RWMutex
relayClient relayRuntimeClient
relayCancel context.CancelFunc
@@ -288,7 +289,10 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monit
// Load persisted and environment-backed SSO before routes begin serving.
// Configuration transfer and no-auth recovery must never observe the old
// lazy-loading window as an unauthenticated installation.
r.ensureSSOConfig()
ssoConfig := r.ensureSSOConfig()
for i := range ssoConfig.Providers {
r.bindSSOProviderOriginalIssuer(&ssoConfig.Providers[i], false)
}
if err := r.syncSAMLPublicURL(); err != nil {
log.Error().Err(err).Msg("Failed to initialize SAML public URL")
}
@@ -317,7 +321,7 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monit
// Note: TimeoutHandler breaks WebSocket upgrades
devMode := utils.GetenvTrim("FRONTEND_DEV_SERVER") != ""
handler := SecurityHeadersWithConfig(r, allowEmbedding, allowedOrigins, devMode)
handler = ErrorHandler(handler)
handler = errorHandler(handler, func(req *http.Request) string { return muxRouteLabel(r.mux, req) })
handler = DemoModeMiddleware(cfg, handler)
// Create tenant middleware with authorization checker.
@@ -542,11 +546,9 @@ func (r *Router) setupRoutes() {
if r.config == nil {
return false
}
config.Mu.Lock()
tokens := make([]config.APITokenRecord, len(r.config.APITokens))
copy(tokens, r.config.APITokens)
config.Mu.Unlock()
return agentOperationsLoopExternalAgentTokenReady(manifest, tokens, now)
// A shallow copy still shares each record's Metadata map with the
// live inventory, and the readiness check clones every record.
return agentOperationsLoopExternalAgentTokenReady(manifest, snapshotAPITokenRecords(r.config), now)
}))
// Wire pending-approvals into the bundle. The provider resolves
// the approval store at request time so multi-tenant rebuilds
@@ -621,6 +623,7 @@ func (r *Router) setupRoutes() {
orgHandlers := NewOrgHandlers(r.multiTenant, r.mtMonitor, rbacProvider)
orgHandlers.SetHostedMode(r.hostedMode)
orgHandlers.SetAccessPolicy(r.orgAccess)
orgHandlers.SetCredentialRevoker(r.revokeTenantCredentials)
orgHandlers.SetOnDelete(func(ctx context.Context, orgID string) error {
return r.CleanupTenant(ctx, orgID)
})
@@ -769,7 +772,9 @@ func (r *Router) setupRoutes() {
})
r.aiSettingsHandler.SetProposalCatalogFactory(func(orgID string) tools.ProposalCatalog {
return func(ctx context.Context, resourceID string) ([]unifiedresources.ResourceCapability, error) {
return resourceHandlers.ActionLifecycle().Capabilities(ctx, orgID, resourceID)
// An investigation's context names no organization.
orgCtx := context.WithValue(ctx, OrgIDContextKey, approval.NormalizeOrgID(orgID))
return resourceHandlers.ActionLifecycle().Capabilities(orgCtx, orgID, resourceID)
}
})
}
@@ -816,7 +821,7 @@ func (r *Router) setupRoutes() {
if req == nil {
return
}
broadcaster.PublishApprovalPending(AgentEventApprovalPendingPayload{
broadcaster.PublishApprovalPending(req.OrgID, AgentEventApprovalPendingPayload{
ApprovalID: req.ID,
ResourceID: req.CanonicalResourceID(),
TargetType: req.TargetType,
@@ -1035,7 +1040,7 @@ func (r *Router) wireReportingAIResolvers() {
}
}
// CleanupTenant removes all per-tenant resources (RBAC, AI, License) for a deleted org.
// CleanupTenant removes all per-tenant resources (credentials, RBAC, AI, License) for a deleted org.
func (r *Router) CleanupTenant(ctx context.Context, orgID string) error {
orgID = strings.TrimSpace(orgID)
if orgID == "" || orgID == "default" {
@@ -1044,6 +1049,10 @@ func (r *Router) CleanupTenant(ctx context.Context, orgID string) error {
var errs []error
if err := r.revokeTenantCredentials(orgID); err != nil {
errs = append(errs, fmt.Errorf("credential cleanup: %w", err))
}
r.StopPatrolForOrg(orgID)
if r.aiSettingsHandler != nil {
@@ -1086,6 +1095,78 @@ func (r *Router) CleanupTenant(ctx context.Context, orgID string) error {
return nil
}
// revokeTenantCredentials withdraws every instance API token from an
// organization ID and ends its agent command sessions. It runs when the
// organization is deleted and again before the ID is claimed by a new one.
// Org-bound tokens (agent install tokens included) live in the instance
// inventory, not in the organization's directory, and are matched to an
// organization by ID alone. An ID is free to be claimed again once its
// organization is gone, so a credential that outlived the deletion would be
// valid in whichever organization takes the ID next. A save failure leaves the
// inventory untouched and is returned so the caller can abort the change.
func (r *Router) revokeTenantCredentials(orgID string) error {
orgID = strings.TrimSpace(orgID)
if r == nil || r.config == nil || orgID == "" || orgID == "default" {
return nil
}
config.Mu.Lock()
previousTokens := append([]config.APITokenRecord(nil), r.config.APITokens...)
keptTokens := make([]config.APITokenRecord, 0, len(previousTokens))
revoked := 0
for _, record := range previousTokens {
bound := record.GetBoundOrgs()
remaining := slices.DeleteFunc(slices.Clone(bound), func(boundOrgID string) bool {
return strings.TrimSpace(boundOrgID) == orgID
})
if len(remaining) == len(bound) {
keptTokens = append(keptTokens, record)
continue
}
revoked++
// A multi-org token keeps its other organizations.
narrowed := record.Clone()
narrowed.OrgIDs = remaining
if strings.TrimSpace(narrowed.OrgID) == orgID {
narrowed.OrgID = ""
}
// Losing the binding must never widen the token: with no organization
// left it would read as an unbound legacy token, and with only the
// default one left it would start acting for the instance. Remove it.
if len(remaining) == 0 || tokenActsForInstance(&narrowed) {
continue
}
keptTokens = append(keptTokens, narrowed)
}
if revoked > 0 {
r.config.APITokens = keptTokens
r.config.SortAPITokens()
if r.persistence != nil {
if err := r.persistence.SaveAPITokens(r.config.APITokens); err != nil {
r.config.APITokens = previousTokens
r.config.SortAPITokens()
config.Mu.Unlock()
return fmt.Errorf("persist API token revocation: %w", err)
}
}
}
config.Mu.Unlock()
if revoked > 0 {
log.Info().
Str("org_id", orgID).
Int("tokens", revoked).
Msg("Revoked API tokens bound to organization ID")
}
if r.agentExecServer != nil {
// Listing revalidates each of the organization's command sessions and
// closes those whose token is gone.
r.agentExecServer.GetConnectedAgentsForOrganization(orgID)
}
return nil
}
// RemoveTenantService removes the cached license service for a deleted org.
func (h *LicenseHandlers) RemoveTenantService(orgID string) {
h.services.Delete(orgID)
@@ -1177,8 +1258,10 @@ func (r *Router) routeAIPatrolFindings(w http.ResponseWriter, req *http.Request)
if !ensureScope(w, req, config.ScopeAIExecute) {
return
}
// Clear all findings - doesn't require Pro license so users can clean up accumulated findings
r.aiSettingsHandler.HandleClearAllFindings(w, req)
// Clear all findings - doesn't require Pro license so users can clean up accumulated findings.
// It erases the organization's whole findings store, so a session
// caller must be one of its managers.
RequireOrgAdmin(r.config, r.aiSettingsHandler.HandleClearAllFindings)(w, req)
default:
if !ensureScope(w, req, config.ScopeAIExecute) {
return
@@ -1281,17 +1364,12 @@ func (r *Router) handleAgentWebSocket(w http.ResponseWriter, req *http.Request)
r.agentExecServer.HandleWebSocket(w, req)
}
// serveSetupTokenOrSettingsWrite gates a privileged settings endpoint behind
// either a valid setup token (setup scripts) or full authentication plus
// proxy-auth admin and settings:write scope. logLabel tags the unauthorized
// log line; nonAdminMsg is the proxy-auth denial log message.
func (r *Router) serveSetupTokenOrSettingsWrite(w http.ResponseWriter, req *http.Request, logLabel, nonAdminMsg string, delegate http.HandlerFunc) {
// Check setup token first (for setup scripts)
if r.isValidSetupTokenForRequest(req) {
delegate(w, req)
return
}
// serveSettingsWrite gates a privileged settings endpoint behind full
// authentication plus proxy-auth admin and settings:write scope. A setup token
// is not accepted: it only authorizes registering the node it was issued for.
// logLabel tags the unauthorized log line; nonAdminMsg is the proxy-auth
// denial log message.
func (r *Router) serveSettingsWrite(w http.ResponseWriter, req *http.Request, logLabel, nonAdminMsg string, delegate http.HandlerFunc) {
// Require authentication
authWriter := &responseCapture{ResponseWriter: w}
if !checkAuth(r.config, authWriter, req, false) {
@@ -1332,44 +1410,16 @@ func (r *Router) handleVerifyTemperatureSSH(w http.ResponseWriter, req *http.Req
http.Error(w, "Service unavailable", http.StatusServiceUnavailable)
return
}
r.serveSetupTokenOrSettingsWrite(w, req, "verify-temperature-ssh", "Non-admin user attempted verify-temperature-ssh", r.configHandlers.HandleVerifyTemperatureSSH)
r.serveSettingsWrite(w, req, "verify-temperature-ssh", "Non-admin user attempted verify-temperature-ssh", r.configHandlers.HandleVerifyTemperatureSSH)
}
// handleSSHConfig handles SSH config writes with setup token or API auth
// handleSSHConfig handles SSH config writes with admin session or API auth
func (r *Router) handleSSHConfig(w http.ResponseWriter, req *http.Request) {
if r.systemSettingsHandler == nil {
http.Error(w, "Service unavailable", http.StatusServiceUnavailable)
return
}
r.serveSetupTokenOrSettingsWrite(w, req, "ssh-config", "Non-admin user attempted ssh-config update", r.systemSettingsHandler.HandleSSHConfig)
}
func extractSetupToken(req *http.Request) string {
if token := strings.TrimSpace(req.Header.Get("X-Setup-Token")); token != "" {
return token
}
if token := extractBearerToken(req.Header.Get("Authorization")); token != "" {
return token
}
return ""
}
func (r *Router) isValidSetupTokenForRequest(req *http.Request) bool {
if r == nil || r.configHandlers == nil || req == nil {
return false
}
token := extractSetupToken(req)
if token == "" {
return false
}
requestOrgID := resolveTenantOrgID(req)
if !isValidOrganizationID(requestOrgID) {
return false
}
return r.configHandlers.ValidateSetupTokenForOrg(token, requestOrgID)
r.serveSettingsWrite(w, req, "ssh-config", "Non-admin user attempted ssh-config update", r.systemSettingsHandler.HandleSSHConfig)
}
func extractBearerToken(header string) string {
@@ -1496,7 +1546,11 @@ func (r *Router) recoverExecutingActions(actor string) {
if ctx.Err() != nil {
return
}
recovered, err := lifecycle.RecoverExecutingActions(ctx, orgID, actor, maxExecutingActionRecoveryBatch)
// Executors resolve the agent session and resources from the context's
// organization. The lifecycle context names none, which reads as the
// default organization, so bind the one whose records are recovered.
orgCtx := context.WithValue(ctx, OrgIDContextKey, orgID)
recovered, err := lifecycle.RecoverExecutingActions(orgCtx, orgID, actor, maxExecutingActionRecoveryBatch)
if err != nil {
log.Warn().Err(err).Str("org_id", orgID).Str("actor", actor).Msg("Executing-action recovery pass failed")
continue
@@ -2992,7 +3046,7 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A
if executor := chatService.GetExecutor(); executor != nil {
broadcaster := r.agentEventBroadcaster
executor.SetOnActionCompleted(func(record unifiedresources.ActionAuditRecord) {
r.publishActionCompletedAgentEvent(broadcaster, record)
r.publishActionCompletedAgentEvent(broadcaster, orgID, record)
})
}
}
@@ -3261,16 +3315,16 @@ func (w *forecastResourceIterator) ForecastStoragePools() []forecast.ResourceInf
return result
}
func (r *Router) publishActionCompletedAgentEvent(broadcaster *AgentEventBroadcaster, record unifiedresources.ActionAuditRecord) {
func (r *Router) publishActionCompletedAgentEvent(broadcaster *AgentEventBroadcaster, orgID string, record unifiedresources.ActionAuditRecord) {
if broadcaster == nil {
return
}
payload, ok := projectAgentActionCompletedPayload(record)
if !ok {
broadcaster.PublishActionCompletedRecord(record)
broadcaster.PublishActionCompletedRecord(orgID, record)
return
}
broadcaster.PublishActionCompleted(payload)
broadcaster.PublishActionCompleted(orgID, payload)
}
func projectAgentActionCompletedPayload(record unifiedresources.ActionAuditRecord) (AgentEventActionCompletedPayload, bool) {
@@ -4368,19 +4422,6 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
isPublic = true
}
// Allow temperature verification endpoint when a setup token is provided
if normalizedPath == "/api/system/verify-temperature-ssh" && r.configHandlers != nil {
if r.isValidSetupTokenForRequest(req) {
isPublic = true
}
}
// Allow SSH config endpoint when a setup token is provided
if normalizedPath == "/api/system/ssh-config" && r.configHandlers != nil {
if r.isValidSetupTokenForRequest(req) {
isPublic = true
}
}
if normalizedPath == "/api/config/export" || normalizedPath == "/api/config/import" {
// These handlers apply stricter route-local auth and public-network checks.
isPublic = true
@@ -4417,6 +4458,12 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
Msg("Unauthorized access attempt")
return
}
// checkAuth accepts Basic credentials only for the configured
// administrator, behind its lockout. canCapturePublicURL leaves
// them to it, so capture for that administrator happens here.
if authWriter.Header().Get("X-Auth-Method") == "basic" {
r.capturePublicURL(req)
}
}
}
// Check CSRF for state-changing requests.
@@ -4500,7 +4547,9 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// This ensures the frontend has a token before making POST requests
if req.Method == "GET" && strings.HasPrefix(req.URL.Path, "/api/") {
sessionCookie, err := readSessionCookie(req)
if err == nil && sessionCookie.Value != "" {
// The cookie value is client-supplied and this runs for public paths too,
// so only a live session may add a token to the persisted CSRF store.
if err == nil && sessionCookie.Value != "" && ValidateSession(sessionCookie.Value) {
// Check if CSRF cookie exists
_, csrfErr := req.Cookie(CookieNameCSRF)
if csrfErr != nil {
@@ -4568,6 +4617,16 @@ func (r *Router) capturePublicURLFromRequest(req *http.Request) {
return
}
r.capturePublicURL(req)
}
// capturePublicURL records the request's origin as the auto-detected public
// URL. The caller has established that the request is an administrator's.
func (r *Router) capturePublicURL(req *http.Request) {
if req == nil || r == nil || r.config == nil || r.hostedMode {
return
}
if r.config.EnvOverrides != nil && r.config.EnvOverrides["publicURL"] {
return
}
@@ -5034,14 +5093,17 @@ func canCapturePublicURL(cfg *config.Config, req *http.Request) bool {
}
}
// API Tokens: Require settings:write scope. This pre-route check runs
// concurrently with authentication. Metadata normalization and LastUsedAt
// need the same exclusive ownership; scope checks use a detached snapshot.
// API Tokens: Require settings:write scope and instance authority, as the
// public URL setting itself does: cfg.APITokens also holds tokens bound to
// tenant organizations, and the URL serves every organization. This
// pre-route check runs concurrently with authentication. Metadata
// normalization and LastUsedAt need the same exclusive ownership; scope
// checks use a detached snapshot.
tokenAllowsCapture := func(token string) bool {
config.Mu.RLock()
defer config.Mu.RUnlock()
record, ok := validateAPITokenLocked(cfg, token)
return ok && record.HasScope(config.ScopeSettingsWrite)
return ok && record.HasScope(config.ScopeSettingsWrite) && tokenActsForInstance(record)
}
if token := strings.TrimSpace(req.Header.Get("X-API-Token")); token != "" {
if tokenAllowsCapture(token) {
@@ -5069,20 +5131,11 @@ func canCapturePublicURL(cfg *config.Config, req *http.Request) bool {
}
}
// Basic Auth: Trusted (Admin)
if cfg.AuthUser != "" && cfg.AuthPass != "" {
const prefix = "Basic "
if authHeader := req.Header.Get("Authorization"); strings.HasPrefix(authHeader, prefix) {
if decoded, err := base64.StdEncoding.DecodeString(authHeader[len(prefix):]); err == nil {
if parts := strings.SplitN(string(decoded), ":", 2); len(parts) == 2 {
if constantTimeStringEqual(parts[0], cfg.AuthUser) && internalauth.CheckPasswordHash(parts[1], cfg.AuthPass) {
return true
}
}
}
}
}
// Basic Auth is not judged here. This check runs before authentication on
// every request, public paths included, where neither the lockout nor a
// rate limit bounds it, and verifying a password costs a bcrypt hash. Only
// checkAuth verifies Basic credentials; ServeHTTP captures once it has
// accepted them.
return false
}
@@ -5158,6 +5211,21 @@ func (r *Router) handleSchedulerHealth(w http.ResponseWriter, req *http.Request)
}
}
// writePasswordChangeLockedOut refuses a password change from an address that
// has used up its failed attempts at the current password.
func writePasswordChangeLockedOut(w http.ResponseWriter, clientIP string, lockedUntil time.Time) {
remainingMinutes := int(time.Until(lockedUntil).Minutes())
if remainingMinutes < 1 {
remainingMinutes = 1
}
log.Warn().
Str("ip", clientIP).
Time("locked_until", lockedUntil).
Msg("Password change blocked - IP locked out")
writeErrorResponse(w, http.StatusForbidden, "locked_out",
fmt.Sprintf("Too many failed attempts. Try again in %d minutes.", remainingMinutes), nil)
}
// handleChangePassword handles password change requests
func (r *Router) handleChangePassword(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
@@ -5188,19 +5256,17 @@ func (r *Router) handleChangePassword(w http.ResponseWriter, req *http.Request)
return
}
// Check lockout status for the client IP
_, lockedUntil, isLocked := GetLockoutInfo(clientIP)
if isLocked {
remainingMinutes := int(time.Until(lockedUntil).Minutes())
if remainingMinutes < 1 {
remainingMinutes = 1
// Check lockout status for the client IP and for the account whose password
// the request tests, as sign-in does. Failures counted per address alone
// let a caller spread guesses over addresses past the account lockout.
_, userLockedUntil, userLocked := GetLockoutInfo(r.config.AuthUser)
_, ipLockedUntil, ipLocked := GetLockoutInfo(clientIP)
if userLocked || ipLocked {
lockedUntil := userLockedUntil
if ipLocked && ipLockedUntil.After(lockedUntil) {
lockedUntil = ipLockedUntil
}
log.Warn().
Str("ip", clientIP).
Time("locked_until", lockedUntil).
Msg("Password change blocked - IP locked out")
writeErrorResponse(w, http.StatusForbidden, "locked_out",
fmt.Sprintf("Too many failed attempts. Try again in %d minutes.", remainingMinutes), nil)
writePasswordChangeLockedOut(w, clientIP, lockedUntil)
return
}
@@ -5224,17 +5290,19 @@ func (r *Router) handleChangePassword(w http.ResponseWriter, req *http.Request)
}
}
// Hold session callers to the same rule the proxy branch above applies.
// Knowing the current password is the real gate on the change itself, so
// this is not an escalation, but without it any authenticated non-admin
// session could probe the admin password one guess at a time and read the
// answer from the 401. ensureAdminSession is a no-op when the request
// carries no session cookie, so the Basic Auth flow is unaffected.
if !ensureAdminSession(r.config, w, req) {
// Hold session and API token callers to the same rule the proxy branch
// above applies. Knowing the current password is the real gate on the
// change itself, so this is not an escalation, but without it any
// authenticated non-admin session, or any API token whatever its scopes,
// could probe the admin password one guess at a time and read the answer
// from the 401. ensureSettingsWriteScope asks an admin session of session
// callers and settings:write of tokens, and is a no-op when the request
// carries neither, so the Basic Auth flow is unaffected.
if !ensureSettingsWriteScope(r.config, w, req) {
log.Warn().
Str("ip", req.RemoteAddr).
Str("path", req.URL.Path).
Msg("Non-admin session attempted to change password")
Msg("Caller without instance settings authority attempted to change password")
return
}
@@ -5292,7 +5360,10 @@ func (r *Router) handleChangePassword(w http.ResponseWriter, req *http.Request)
Str("ip", req.RemoteAddr).
Str("username", username).
Msg("Failed password change attempt - incorrect current password in auth header")
RecordFailedLogin(clientIP)
if lockedUntil, locked := RecordLoginAttempt(false, r.config.AuthUser, clientIP); locked {
writePasswordChangeLockedOut(w, clientIP, lockedUntil)
return
}
writeErrorResponse(w, http.StatusUnauthorized, "unauthorized",
"Current password is incorrect", nil)
return
@@ -5312,13 +5383,25 @@ func (r *Router) handleChangePassword(w http.ResponseWriter, req *http.Request)
Str("ip", req.RemoteAddr).
Str("username", username).
Msg("Failed password change attempt - incorrect current password")
RecordFailedLogin(clientIP)
if lockedUntil, locked := RecordLoginAttempt(false, r.config.AuthUser, clientIP); locked {
writePasswordChangeLockedOut(w, clientIP, lockedUntil)
return
}
writeErrorResponse(w, http.StatusUnauthorized, "unauthorized",
"Current password is incorrect", nil)
return
}
}
// The lockout check above ran before the current password was hashed, so
// guesses sent together all passed it. One that was still being verified
// when the account or address reached its limit is refused even though it
// is right, as RecordLoginAttempt refuses the wrong ones.
if lockedUntil, locked := RecordLoginAttempt(true, r.config.AuthUser, clientIP); locked {
writePasswordChangeLockedOut(w, clientIP, lockedUntil)
return
}
// Hash the new password before storing
hashedPassword, err := auth.HashPassword(changeReq.NewPassword)
if err != nil {
@@ -5631,22 +5714,7 @@ func (r *Router) handleLogin(w http.ResponseWriter, req *http.Request) {
if ipLocked && ipLockedUntil.After(lockedUntil) {
lockedUntil = ipLockedUntil
}
remainingMinutes := int(time.Until(lockedUntil).Minutes())
if remainingMinutes < 1 {
remainingMinutes = 1
}
LogAuditEventForTenant(GetOrgID(req.Context()), "login", loginReq.Username, clientIP, req.URL.Path, false, "Account locked")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(map[string]interface{}{
"error": "account_locked",
"message": fmt.Sprintf("Too many failed attempts. Account is locked for %d more minutes.", remainingMinutes),
"lockedUntil": lockedUntil.Format(time.RFC3339),
"remainingMinutes": remainingMinutes,
})
writeLoginLockedOut(w, req, loginReq.Username, clientIP, lockedUntil)
return
}
@@ -5673,11 +5741,15 @@ func (r *Router) handleLogin(w http.ResponseWriter, req *http.Request) {
credentialsValid = true
effectiveUsername = "admin"
}
// The lockout check above ran before the password was hashed, so attempts
// sent together all passed it. Count this one in the same step that asks
// whether the limit was reached meanwhile: if it was, the attempt is
// refused whatever its result. A success clears the failed attempts.
if lockedUntil, locked := RecordLoginAttempt(credentialsValid, loginReq.Username, clientIP); locked {
writeLoginLockedOut(w, req, loginReq.Username, clientIP, lockedUntil)
return
}
if credentialsValid {
// Clear failed login attempts
ClearFailedLogins(loginReq.Username)
ClearFailedLogins(clientIP)
// Invalidate any pre-existing session to prevent session fixation attacks.
InvalidateOldSessionFromRequest(req)
@@ -5736,9 +5808,7 @@ func (r *Router) handleLogin(w http.ResponseWriter, req *http.Request) {
"message": "Successfully logged in",
})
} else {
// Failed login
RecordFailedLogin(loginReq.Username)
RecordFailedLogin(clientIP)
// Failed login, counted by RecordLoginAttempt above
LogAuditEventForTenant(GetOrgID(req.Context()), "login", loginReq.Username, clientIP, req.URL.Path, false, "Invalid credentials")
// Get updated attempt counts
@@ -5776,6 +5846,26 @@ func (r *Router) handleLogin(w http.ResponseWriter, req *http.Request) {
}
}
// writeLoginLockedOut refuses a login for a username or address that has used
// up its failed attempts.
func writeLoginLockedOut(w http.ResponseWriter, req *http.Request, username, clientIP string, lockedUntil time.Time) {
remainingMinutes := int(time.Until(lockedUntil).Minutes())
if remainingMinutes < 1 {
remainingMinutes = 1
}
LogAuditEventForTenant(GetOrgID(req.Context()), "login", username, clientIP, req.URL.Path, false, "Account locked")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(map[string]interface{}{
"error": "account_locked",
"message": fmt.Sprintf("Too many failed attempts. Account is locked for %d more minutes.", remainingMinutes),
"lockedUntil": lockedUntil.Format(time.RFC3339),
"remainingMinutes": remainingMinutes,
})
}
// handleResetLockout allows administrators to manually reset account lockouts
func (r *Router) handleResetLockout(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
@@ -8116,7 +8206,7 @@ func (r *Router) handleDiagnosticsDockerPrepareToken(w http.ResponseWriter, req
EnableHost *bool `json:"enableHost,omitempty"`
}
if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, req.Body, 8*1024)).Decode(&payload); err != nil {
writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Failed to decode request body", nil)
return
}
@@ -8217,39 +8307,26 @@ func (r *Router) handleDiagnosticsDockerPrepareToken(w http.ResponseWriter, req
}
setAPITokenOwnerUserID(record, apiTokenOwnerUserIDForRequest(r.config, req))
activeConfig := r.config
activePersistence := r.persistence
if orgID != "" && orgID != "default" {
activeConfig = monitor.GetConfig()
if activeConfig == nil {
writeErrorResponse(w, http.StatusInternalServerError, "tenant_config_unavailable", "Tenant config is not available", nil)
return
}
if r.multiTenant == nil {
writeErrorResponse(w, http.StatusInternalServerError, "tenant_persistence_unavailable", "Tenant persistence is not configured", nil)
return
}
tenantPersistence, err := r.multiTenant.GetPersistence(orgID)
if err != nil {
writeErrorResponse(w, http.StatusInternalServerError, "tenant_persistence_unavailable", "Failed to resolve tenant persistence", nil)
return
}
activePersistence = tenantPersistence
}
if activeConfig == nil {
// A tenant organization's record also goes into the instance inventory,
// bound to it by OrgID, the same as agenttokens.IssueAndPersistForOrganization.
// That is the inventory header-less agents authenticate against and the
// only one /api/security/tokens lists, revokes and rotates. A record kept
// in the organization's own config copy still authenticates requests that
// name the organization, and no token route can show or revoke it.
if r.config == nil {
writeErrorResponse(w, http.StatusInternalServerError, "config_unavailable", "Configuration is not loaded", nil)
return
}
config.Mu.Lock()
previousTokens := append([]config.APITokenRecord(nil), activeConfig.APITokens...)
activeConfig.APITokens = append(activeConfig.APITokens, *record)
activeConfig.SortAPITokens()
previousTokens := append([]config.APITokenRecord(nil), r.config.APITokens...)
r.config.APITokens = append(r.config.APITokens, *record)
r.config.SortAPITokens()
if activePersistence != nil {
if err := activePersistence.SaveAPITokens(activeConfig.APITokens); err != nil {
activeConfig.APITokens = previousTokens
activeConfig.SortAPITokens()
if r.persistence != nil {
if err := r.persistence.SaveAPITokens(r.config.APITokens); err != nil {
r.config.APITokens = previousTokens
r.config.SortAPITokens()
config.Mu.Unlock()
log.Error().Err(err).Msg("Failed to persist API tokens after container runtime migration generation")
writeErrorResponse(w, http.StatusInternalServerError, "token_persist_failed", "Failed to persist API token", nil)
@@ -15,6 +15,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"
unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
// callbackLossDockerExecutor simulates a server that dies (or loses the agent
@@ -256,3 +257,79 @@ func TestRouterRecoverExecutingDockerUpdateAfterCapabilityDisappears(t *testing.
t.Fatalf("receipt queries=%d, want one", len(agents.queries))
}
}
// receiptQueryOrgExecutor loses every dispatch callback and records which
// organization its reconciler would query for the receipt.
type receiptQueryOrgExecutor struct {
queriedOrgs []string
}
func (e *receiptQueryOrgExecutor) ExecuteAction(context.Context, unified.ActionAuditRecord) (*unified.ExecutionResult, error) {
return nil, errors.New("simulated callback loss after transport send")
}
func (e *receiptQueryOrgExecutor) ReconcileActionDispatch(ctx context.Context, _ unified.ActionAuditRecord, _ unified.ActionDispatchAttempt) (*unified.ExecutionResult, unified.ActionDispatchReceipt, bool, error) {
e.queriedOrgs = append(e.queriedOrgs, GetOrgID(ctx))
return nil, unified.ActionDispatchReceipt{}, false, nil
}
// The recovery pass walks every organization from one lifecycle context.
// Executors take the organization of the agent session from the context, so
// an organization's receipt must be asked of its own agents and never of the
// default organization's.
func TestRouterRecoverExecutingActionsQueriesTheActionsOwnOrganization(t *testing.T) {
now := time.Now().UTC()
resource := dockerContainerActionResource("app-container:api", "docker", "running", now)
cfg := &config.Config{DataPath: t.TempDir()}
h := newActionTestResourceHandlers(t, cfg)
h.SetTenantStateProvider(assistantTenantSeedProvider{orgID: "acme", snapshot: models.StateSnapshot{LastUpdate: now}, vm: resource})
executor := &receiptQueryOrgExecutor{}
h.SetActionExecutor(executor)
persistence := config.NewMultiTenantPersistence(cfg.DataPath)
if err := persistence.SaveOrganization(&models.Organization{ID: "acme", DisplayName: "Acme"}); err != nil {
t.Fatal(err)
}
acmeRequest := func(req *http.Request) *http.Request {
actor := unified.ActionActor{SubjectID: "operator@example.com", Kind: unified.ActionActorUser, CredentialID: "session:test", OrgID: "acme"}
ctx := context.WithValue(req.Context(), OrgIDContextKey, "acme")
return req.WithContext(withTrustedActionActor(auth.WithUser(ctx, actor.SubjectID), actor))
}
planRec := httptest.NewRecorder()
h.HandlePlanAction(planRec, acmeRequest(httptest.NewRequest(http.MethodPost, "/api/actions/plan", bytes.NewBufferString(`{
"requestId":"req-acme-recovery",
"resourceId":"app-container:api",
"capabilityName":"restart",
"reason":"exercise tenant recovery"
}`))))
var plan unified.ActionPlan
if err := json.Unmarshal(planRec.Body.Bytes(), &plan); planRec.Code != http.StatusOK || err != nil || plan.ActionID == "" {
t.Fatalf("plan status=%d err=%v body=%s", planRec.Code, err, planRec.Body.String())
}
decisionRec := httptest.NewRecorder()
decisionReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+plan.ActionID+"/decision", bytes.NewBufferString(`{"outcome":"approved","reason":"controlled recovery proof"}`))
decisionReq.SetPathValue("id", plan.ActionID)
h.HandleDecideAction(decisionRec, acmeRequest(decisionReq))
if decisionRec.Code != http.StatusOK {
t.Fatalf("decision status=%d body=%s", decisionRec.Code, decisionRec.Body.String())
}
executionReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+plan.ActionID+"/execute", bytes.NewBufferString(`{"reason":"controlled callback loss"}`))
executionReq.SetPathValue("id", plan.ActionID)
h.HandleExecuteAction(httptest.NewRecorder(), acmeRequest(executionReq))
store, err := h.getStore("acme")
if err != nil {
t.Fatal(err)
}
attempt, found, err := store.GetActionDispatchAttempt(plan.ActionID)
if err != nil || !found || attempt.State != unified.ActionDispatchReceiptPending {
t.Fatalf("pending attempt found=%v err=%v attempt=%#v", found, err, attempt)
}
router := &Router{resourceHandlers: h, multiTenant: persistence}
router.recoverExecutingActions("system:periodic-recovery")
if len(executor.queriedOrgs) != 1 || executor.queriedOrgs[0] != "acme" {
t.Fatalf("receipt queried in organizations %q, want only acme", executor.queriedOrgs)
}
}
@@ -78,6 +78,4 @@ var authBypassAllowlist = []string{
"/api/config/export",
"/api/config/import",
"/api/setup-script",
"/api/system/ssh-config",
"/api/system/verify-temperature-ssh",
}
@@ -334,3 +334,41 @@ func TestRouterDoesNotIssueCSRFCookieWithoutSession(t *testing.T) {
}
}
}
// Public paths pass the global auth gate, so the cookie alone must not be
// enough for the router to add a token to the persisted CSRF store.
func TestRouterDoesNotIssueCSRFCookieForUnknownSession(t *testing.T) {
router, _ := newRouterWithSession(t)
router.mux.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
for _, method := range []string{http.MethodGet, http.MethodPost} {
req := httptest.NewRequest(method, "/api/health", nil)
req.AddCookie(&http.Cookie{Name: "pulse_session", Value: "made-up-session"})
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
wantStatus := http.StatusOK
if method == http.MethodPost {
wantStatus = http.StatusForbidden
}
if rec.Code != wantStatus {
t.Fatalf("%s: expected status %d, got %d (%s)", method, wantStatus, rec.Code, rec.Body.String())
}
if token := rec.Header().Get("X-CSRF-Token"); token != "" {
t.Fatalf("%s: did not expect a replacement CSRF token header, got %q", method, token)
}
for _, c := range rec.Result().Cookies() {
if c.Name == "pulse_csrf" && c.Value != "" {
t.Fatalf("%s: did not expect pulse_csrf cookie to be set", method)
}
}
}
if sessions := csrfSessionCountForTest(); sessions != 0 {
t.Fatalf("expected no CSRF records for unknown sessions, got %d", sessions)
}
}
@@ -60,43 +60,6 @@ func TestExtractBearerToken(t *testing.T) {
}
}
func TestExtractSetupToken(t *testing.T) {
t.Run("prefers header token", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/setup?auth_token=query-token", nil)
req.Header.Set("X-Setup-Token", " header-token ")
req.Header.Set("Authorization", "Bearer auth-token")
if got := extractSetupToken(req); got != "header-token" {
t.Fatalf("expected header token, got %q", got)
}
})
t.Run("falls back to bearer", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/setup?auth_token=query-token", nil)
req.Header.Set("X-Setup-Token", " ")
req.Header.Set("Authorization", "Bearer auth-token")
if got := extractSetupToken(req); got != "auth-token" {
t.Fatalf("expected bearer token, got %q", got)
}
})
t.Run("ignores query auth_token", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/setup?auth_token=query-token", nil)
if got := extractSetupToken(req); got != "" {
t.Fatalf("expected empty token, got %q", got)
}
})
t.Run("returns empty when missing", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/setup", nil)
if got := extractSetupToken(req); got != "" {
t.Fatalf("expected empty token, got %q", got)
}
})
}
func TestFileExists(t *testing.T) {
dir := t.TempDir()
filePath := filepath.Join(dir, "exists.txt")

Some files were not shown because too many files have changed in this diff Show More