mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-03 18:43:38 +01:00
Keep token-control transactions on live caller authority (#4544)
**Keep token-control transactions on live caller authority** Recheck the admitted token in its live inventory under the same configuration writer lock as creation, edit, revocation and rotation. Use current scopes, credential identity and boundaries after slow input or lock waits; retain typed 401/403 denials, valid self-change, persistence rollback and unlocked audit/HTTP I/O. Contract-Neutral: Enforce existing token withdrawal, scope and organization boundaries at credential transaction admission; preserve routes, response schemas, grants, non-token admission and valid relay compatibility without adding a capability. **Preserve first-match credential admission and tenant issuer proof** Keep transaction revalidation on authentication's first matching credential hash. Exercise shadowing and exact cached tenant ownership without starting a monitor, and keep invalid in-memory role controls distinct from persistence's existing rejection. Contract-Neutral: Preserve existing first-match token authentication and scoped issuer ownership at the transaction fence; no route, grant, stored format or response schema changes. **Admit the tenant owner before introducing a fallback copy** The ownership fixture must authenticate against the cached tenant inventory first: an existing global copy intentionally wins initial authentication. Add the global decoy after admission so live compatibility and withdrawal actually exercise the intended owner. **Give the delete-scope contract a live token caller** The containing API shard reached credential withdrawal before the intended target-scope denial because its caller existed only in context. Keep the 403 scope contract with a real live caller, add an explicit 401 withdrawn-context control, and prove the full target/caller inventory remains unchanged. No runtime authorization check or response contract is weakened. --- Fleet candidate `20261117T112221Z-core-runtime` from the `core-runtime` lane. Reviewed tip `72c6ba825536bee6cf79be8a000fca0ab2c9ccac` on `main`. [How Pulse handles triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
10 files changed
+752
-66
No files matched your search
@@ -18,6 +18,33 @@
|
||||
|
||||
## Purpose
|
||||
|
||||
### API-token control follows live authority through its transaction (17 November 2026)
|
||||
|
||||
An admitted token snapshot does not grant a later credential mutation. Token
|
||||
creation, metadata/scope edits, revocation and rotation resolve that caller's
|
||||
live ID, credential hash and principal while holding the same configuration
|
||||
writer lock as the saved inventory transition. A slow request body or a wait
|
||||
for configuration ownership cannot outlive credential withdrawal. Current
|
||||
expiry, runtime-role validity, settings-write scope, organization access and
|
||||
the admitted instance boundary apply before target/grant checks or mutation.
|
||||
Those target and grant checks use the current caller, not its earlier scopes.
|
||||
Revoked, expired, replaced or differently owned credentials receive 401;
|
||||
a still-valid credential that lost a needed privilege receives 403. Refused
|
||||
writes neither issue a secret nor change the live or saved credential inventory.
|
||||
|
||||
Valid self-rotation, self-revocation and self-narrowing remain possible. The
|
||||
shared issuer retains its existing organization-scoped relay compatibility;
|
||||
this adds no Mobile capability. Session/proxy admission stays with existing
|
||||
route policy. Body reads, audit destinations and HTTP output remain outside
|
||||
configuration ownership, and persistence failure retains existing rollback.
|
||||
`internal/api/security_token_withdrawal_test.go` exercises paused registered
|
||||
routes with independent durable admin withdrawal, old admitted transactions,
|
||||
current grant containment and live self-change. Existing token tests retain
|
||||
their target/organization, private snapshot, failed-save and I/O boundaries.
|
||||
These synthetic proofs do not establish historical exposure, original-client
|
||||
recovery or installed availability.
|
||||
|
||||
|
||||
### Public OIDC login bounds input before IdP work (16 November 2026)
|
||||
|
||||
`handleSSOOIDCLogin` reuses the existing whole-document 16 KiB security JSON
|
||||
|
||||
@@ -10403,43 +10403,77 @@ func TestContract_HostedDirectCloudHandoffUsesExistingTenantMembership(t *testin
|
||||
}
|
||||
|
||||
func TestContract_APITokenDeleteRejectsScopeEscalation(t *testing.T) {
|
||||
router := &Router{
|
||||
config: &config.Config{
|
||||
APITokens: []config.APITokenRecord{
|
||||
{
|
||||
ID: "broad-token",
|
||||
Name: "broad",
|
||||
Hash: "hash-broad",
|
||||
CreatedAt: time.Now().Add(-time.Hour),
|
||||
Scopes: []string{config.ScopeWildcard},
|
||||
OrgID: "default",
|
||||
},
|
||||
},
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
withdraw bool
|
||||
wantStatus int
|
||||
wantBody string
|
||||
}{
|
||||
{
|
||||
name: "live limited caller",
|
||||
wantStatus: http.StatusForbidden,
|
||||
wantBody: `Cannot delete token with scope "*"`,
|
||||
},
|
||||
}
|
||||
{
|
||||
name: "withdrawn caller",
|
||||
withdraw: true,
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
wantBody: "Invalid API token",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
router := &Router{
|
||||
config: &config.Config{
|
||||
APITokens: []config.APITokenRecord{
|
||||
{
|
||||
ID: "broad-token",
|
||||
Name: "broad",
|
||||
Hash: "hash-broad",
|
||||
CreatedAt: time.Now().Add(-time.Hour),
|
||||
Scopes: []string{config.ScopeWildcard},
|
||||
OrgID: "default",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
caller, err := config.NewAPITokenRecord(
|
||||
"limited-caller-token-123.12345678",
|
||||
"limited",
|
||||
[]string{config.ScopeSettingsWrite},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAPITokenRecord: %v", err)
|
||||
}
|
||||
caller, err := config.NewAPITokenRecord(
|
||||
"limited-caller-token-123.12345678",
|
||||
"limited",
|
||||
[]string{config.ScopeSettingsWrite},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAPITokenRecord: %v", err)
|
||||
}
|
||||
// Model the live inventory that admitted the request, not a caller
|
||||
// invented only in context. A later withdrawal keeps that detached
|
||||
// context but must be rejected before the target-scope check.
|
||||
router.config.UpsertAPIToken(*caller)
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/security/tokens/broad-token", nil)
|
||||
req = req.WithContext(authpkg.WithAPIToken(req.Context(), caller))
|
||||
if tc.withdraw {
|
||||
if removed := router.config.RemoveAPIToken(caller.ID); removed == nil {
|
||||
t.Fatal("failed to withdraw the admitted caller")
|
||||
}
|
||||
}
|
||||
before := make([]config.APITokenRecord, len(router.config.APITokens))
|
||||
for i := range before {
|
||||
before[i] = router.config.APITokens[i].Clone()
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/security/tokens/broad-token", nil)
|
||||
req = req.WithContext(authpkg.WithAPIToken(req.Context(), caller))
|
||||
rec := httptest.NewRecorder()
|
||||
router.handleDeleteAPIToken(rec, req)
|
||||
rec := httptest.NewRecorder()
|
||||
router.handleDeleteAPIToken(rec, req)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusForbidden)
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), `Cannot delete token with scope "*"`) {
|
||||
t.Fatalf("expected delete scope-escalation contract message, got %q", rec.Body.String())
|
||||
}
|
||||
if len(router.config.APITokens) != 1 || router.config.APITokens[0].ID != "broad-token" {
|
||||
t.Fatalf("expected broader token to remain configured, got %+v", router.config.APITokens)
|
||||
if rec.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d: %s", rec.Code, tc.wantStatus, rec.Body.String())
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), tc.wantBody) {
|
||||
t.Fatalf("expected delete contract message %q, got %q", tc.wantBody, rec.Body.String())
|
||||
}
|
||||
if !reflect.DeepEqual(router.config.APITokens, before) {
|
||||
t.Fatal("denied delete changed the target or caller inventory")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
||||
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
|
||||
)
|
||||
|
||||
// tokenMutationFailure is returned while config.Mu is held, but is written
|
||||
// only after releasing it. Refusing a still-valid credential's lost privilege
|
||||
// must not tell clients that the credential itself has become invalid.
|
||||
type tokenMutationFailure struct {
|
||||
status int
|
||||
message string
|
||||
missingScope bool
|
||||
}
|
||||
|
||||
func (f *tokenMutationFailure) Error() string { return f.message }
|
||||
|
||||
func (f *tokenMutationFailure) write(w http.ResponseWriter) {
|
||||
if f.missingScope {
|
||||
respondMissingScope(w, config.ScopeSettingsWrite)
|
||||
return
|
||||
}
|
||||
http.Error(w, f.message, f.status)
|
||||
}
|
||||
|
||||
// currentTokenMutationCallerLocked rechecks the route's admitted token under
|
||||
// the same config writer lock as the inventory transaction. Body reads and
|
||||
// waiting for this lock can outlive revocation, rotation or a scope edit.
|
||||
// The detached request record identifies the credential, not a lasting grant.
|
||||
// Non-token authentication remains the route's responsibility.
|
||||
func (r *Router) currentTokenMutationCallerLocked(req *http.Request) (*config.APITokenRecord, *tokenMutationFailure) {
|
||||
admitted := getAPITokenRecordFromRequest(req)
|
||||
if admitted == nil {
|
||||
return nil, nil
|
||||
}
|
||||
invalid := &tokenMutationFailure{status: http.StatusUnauthorized, message: "Invalid API token"}
|
||||
live := r.config
|
||||
if source, ok := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource); ok && source.orgID != "" && source.orgID != "default" {
|
||||
// The shared issuer also serves organization-scoped relay credentials.
|
||||
// Never fall back to another inventory when that owner is withdrawn.
|
||||
live = tenantTokenConfigForRequest(req)
|
||||
}
|
||||
if live == nil {
|
||||
return nil, invalid
|
||||
}
|
||||
for i := range live.APITokens {
|
||||
current := &live.APITokens[i]
|
||||
if !constantTimeStringEqual(current.Hash, admitted.Hash) {
|
||||
continue
|
||||
}
|
||||
// Authentication chooses the first matching credential hash. A newly
|
||||
// shadowing record must not let an older context choose a later grant.
|
||||
if current.ID != admitted.ID {
|
||||
return nil, invalid
|
||||
}
|
||||
role := strings.TrimSpace(current.Metadata[internalauth.RuntimeRoleMetadataKey])
|
||||
if current.IsExpired() || apiTokenAuthenticatedUser(current) != apiTokenAuthenticatedUser(admitted) ||
|
||||
internalauth.ValidateRoleScopes(role, current.Scopes) != nil {
|
||||
return nil, invalid
|
||||
}
|
||||
if !current.HasScope(config.ScopeSettingsWrite) {
|
||||
return nil, &tokenMutationFailure{status: http.StatusForbidden, message: "Missing settings:write scope", missingScope: true}
|
||||
}
|
||||
// Keep the route's original instance boundary, without imposing one on
|
||||
// the existing org-scoped issuer. A binding edit cannot turn an admitted
|
||||
// instance request into permission to mutate the global inventory.
|
||||
if (tokenActsForInstance(admitted) && !tokenActsForInstance(current)) ||
|
||||
!NewAuthorizationChecker(nil).CheckAccess(current, "", GetOrgID(req.Context())).Allowed {
|
||||
return nil, &tokenMutationFailure{status: http.StatusForbidden, message: "Admin privileges required"}
|
||||
}
|
||||
clone := current.Clone()
|
||||
attachAPITokenRecord(req, &clone)
|
||||
return &clone, nil
|
||||
}
|
||||
return nil, invalid
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -52,7 +53,7 @@ func TestSecurityTokenMutationIOReleasesConfig(t *testing.T) {
|
||||
for _, scenario := range scenarios {
|
||||
t.Run(operation+"/"+scenario, func(t *testing.T) {
|
||||
f := newOrgTokenFixture(t)
|
||||
caller, target := f.def.Clone(), f.orgB.Clone()
|
||||
caller, target := newTokenRecord(t, "synthetic-isolation-caller.12345678", []string{config.ScopeWildcard}, nil), f.orgB.Clone()
|
||||
body := `{"name":"edited","scopes":["monitoring:read"]}`
|
||||
wantStatus, wantBody := http.StatusOK, ""
|
||||
switch scenario {
|
||||
@@ -83,6 +84,7 @@ func TestSecurityTokenMutationIOReleasesConfig(t *testing.T) {
|
||||
wantBody = "Cannot grant scope \"*\" in the default organization: your token is not an instance-wide full-access token\n"
|
||||
}
|
||||
}
|
||||
f.cfg.UpsertAPIToken(caller)
|
||||
f.cfg.SortAPITokens()
|
||||
before := make([]config.APITokenRecord, len(f.cfg.APITokens))
|
||||
for i := range f.cfg.APITokens {
|
||||
@@ -136,6 +138,9 @@ func TestSecurityTokenMutationIOReleasesConfig(t *testing.T) {
|
||||
logger := installTokenMutationAuditProbe(t, func() { probe("audit") })
|
||||
writer := &tokenReadProbeWriter{ResponseRecorder: httptest.NewRecorder(), probe: func() { probe("response") }}
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if caller.OrgID != "" {
|
||||
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, caller.OrgID))
|
||||
}
|
||||
attachAPITokenRecord(req, &caller)
|
||||
handler(writer, req)
|
||||
if !writer.probed || writer.Code != wantStatus {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -47,6 +48,9 @@ func newOrgTokenFixture(t *testing.T) *orgTokenFixture {
|
||||
// call runs a token-management handler as the given caller token.
|
||||
func (f *orgTokenFixture) call(caller *config.APITokenRecord, method, path string, handler func(http.ResponseWriter, *http.Request)) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(`{"name":"renamed"}`))
|
||||
if caller != nil && len(caller.OrgIDs) == 0 && caller.OrgID != "" {
|
||||
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, caller.OrgID))
|
||||
}
|
||||
attachAPITokenRecord(req, caller)
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
|
||||
"github.com/rcourtman/pulse-go-rewrite/pkg/audit"
|
||||
)
|
||||
|
||||
// A complete, bounded JSON document may still arrive after its caller's
|
||||
// credential changes. The real route must not turn that old admission into a
|
||||
// new credential, or edit a credential after withdrawal has committed.
|
||||
type tokenWithdrawalBody struct {
|
||||
io.Reader
|
||||
started chan struct{}
|
||||
resume chan struct{}
|
||||
read bool
|
||||
}
|
||||
|
||||
func (b *tokenWithdrawalBody) Read(p []byte) (int, error) {
|
||||
if !b.read {
|
||||
b.read = true
|
||||
close(b.started)
|
||||
<-b.resume
|
||||
}
|
||||
return b.Reader.Read(p)
|
||||
}
|
||||
func (b *tokenWithdrawalBody) Close() error { return nil }
|
||||
|
||||
func tokenWithdrawalFixture(t *testing.T) (*Router, *config.Config, config.APITokenRecord, config.APITokenRecord) {
|
||||
t.Helper()
|
||||
caller := newTokenRecord(t, "synthetic-withdrawal-caller.12345678", []string{config.ScopeWildcard}, nil)
|
||||
caller.ID, caller.Name, caller.OrgID = "fixture-caller", "Automation manager", "default"
|
||||
target := newTokenRecord(t, "synthetic-withdrawal-target.12345678", []string{config.ScopeMonitoringRead}, nil)
|
||||
target.ID, target.Name, target.OrgID = "fixture-target", "Saved collector", "default"
|
||||
target.Prefix, target.Suffix = "test", "1234"
|
||||
target.CreatedAt = time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
|
||||
admin := newTokenRecord(t, "synthetic-withdrawal-admin.12345678", []string{config.ScopeWildcard}, nil)
|
||||
admin.ID, admin.Name, admin.OrgID = "fixture-admin", "Independent admin", "default"
|
||||
cfg := newTestConfigWithTokens(t, caller, target, admin)
|
||||
router := newTestRouter(t, cfg, nil, nil, nil, nil, "test")
|
||||
return router, cfg, caller, target
|
||||
}
|
||||
|
||||
func tokenWithdrawalInventory(t *testing.T, router *Router) []byte {
|
||||
t.Helper()
|
||||
config.Mu.RLock()
|
||||
defer config.Mu.RUnlock()
|
||||
b, err := json.Marshal(router.config.APITokens)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func TestSecurityTokenMutationRoutesFollowCallerWithdrawal(t *testing.T) {
|
||||
t.Setenv("ALLOW_ADMIN_BYPASS", "")
|
||||
resetAdminBypassState()
|
||||
t.Cleanup(resetAdminBypassState)
|
||||
for _, operation := range []string{"create", "rename", "scope"} {
|
||||
for _, change := range []string{"revoked", "rotated", "scope removed", "expired", "rebound", "owner changed"} {
|
||||
t.Run(operation+"/"+change, func(t *testing.T) {
|
||||
router, cfg, caller, target := tokenWithdrawalFixture(t)
|
||||
method, path, body := http.MethodPatch, "/api/security/tokens/"+target.ID, `{"name":"Current collector"}`
|
||||
if operation == "create" {
|
||||
method, path, body = http.MethodPost, "/api/security/tokens", `{"name":"New collector","scopes":["monitoring:read"]}`
|
||||
} else if operation == "scope" {
|
||||
body = `{"scopes":["settings:read"]}`
|
||||
}
|
||||
paused := &tokenWithdrawalBody{Reader: strings.NewReader(body), started: make(chan struct{}), resume: make(chan struct{})}
|
||||
req := httptest.NewRequest(method, path, paused)
|
||||
req.Header.Set("X-API-Token", "synthetic-withdrawal-caller.12345678")
|
||||
rec := httptest.NewRecorder()
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); router.Handler().ServeHTTP(rec, req) }()
|
||||
// Release and join on every assertion path; no detached request may keep
|
||||
// writing its test's state after cleanup.
|
||||
released := false
|
||||
defer func() {
|
||||
if !released {
|
||||
close(paused.resume)
|
||||
}
|
||||
<-done
|
||||
}()
|
||||
select {
|
||||
case <-paused.started:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("registered route did not reach its body reader")
|
||||
}
|
||||
wantStatus := http.StatusUnauthorized
|
||||
switch change {
|
||||
case "revoked", "rotated", "scope removed":
|
||||
adminMethod, adminPath, adminBody := http.MethodDelete, "/api/security/tokens/"+caller.ID, ""
|
||||
adminStatus := http.StatusNoContent
|
||||
if change == "rotated" {
|
||||
adminMethod, adminPath, adminStatus = http.MethodPost, adminPath+"/rotate", http.StatusOK
|
||||
}
|
||||
if change == "scope removed" {
|
||||
adminMethod, adminBody, adminStatus = http.MethodPatch, `{"scopes":["settings:read","monitoring:read"]}`, http.StatusOK
|
||||
wantStatus = http.StatusForbidden
|
||||
}
|
||||
adminReq := httptest.NewRequest(adminMethod, adminPath, strings.NewReader(adminBody))
|
||||
adminReq.Header.Set("X-API-Token", "synthetic-withdrawal-admin.12345678")
|
||||
adminRec := httptest.NewRecorder()
|
||||
router.Handler().ServeHTTP(adminRec, adminReq)
|
||||
if adminRec.Code != adminStatus {
|
||||
t.Fatalf("independent withdrawal status=%d, want %d", adminRec.Code, adminStatus)
|
||||
}
|
||||
default:
|
||||
config.Mu.Lock()
|
||||
for i := range cfg.APITokens {
|
||||
if cfg.APITokens[i].ID != caller.ID {
|
||||
continue
|
||||
}
|
||||
switch change {
|
||||
case "expired":
|
||||
expires := time.Now().Add(-time.Second)
|
||||
cfg.APITokens[i].ExpiresAt = &expires
|
||||
case "rebound":
|
||||
cfg.APITokens[i].OrgID = "different-estate"
|
||||
wantStatus = http.StatusForbidden
|
||||
case "owner changed":
|
||||
cfg.APITokens[i].Metadata = map[string]string{apiTokenMetadataOwnerUserID: "different-owner"}
|
||||
}
|
||||
}
|
||||
cfg.SortAPITokens()
|
||||
err := router.persistence.SaveAPITokens(cfg.APITokens)
|
||||
config.Mu.Unlock()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
before := tokenWithdrawalInventory(t, router)
|
||||
durableBefore, err := router.persistence.LoadAPITokens()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
close(paused.resume)
|
||||
released = true
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("request did not finish after its body resumed")
|
||||
}
|
||||
// Native producer bytes for the consuming browser proof. Only the
|
||||
// credential-free rename and scope responses are emitted; no raw issued
|
||||
// secret/hash is ever logged.
|
||||
if operation != "create" && (change == "scope removed" || change == "revoked") {
|
||||
artifact := map[string]any{"operation": operation, "change": change, "status": rec.Code, "content_type": rec.Header().Get("Content-Type"), "body": rec.Body.String(), "initial": toAPITokenDTO(target)}
|
||||
encoded, marshalErr := json.Marshal(artifact)
|
||||
if marshalErr != nil {
|
||||
t.Fatal(marshalErr)
|
||||
}
|
||||
fmt.Printf("TOKEN_WITHDRAWAL_PRODUCER %s\n", encoded)
|
||||
}
|
||||
if rec.Code != wantStatus {
|
||||
t.Errorf("withdrawn caller mutation status=%d, want %d", rec.Code, wantStatus)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), `"token":`) {
|
||||
t.Error("withdrawn caller received a new credential")
|
||||
}
|
||||
if got := tokenWithdrawalInventory(t, router); string(got) != string(before) {
|
||||
t.Error("withdrawn caller changed the post-withdrawal live inventory")
|
||||
}
|
||||
durableAfter, err := router.persistence.LoadAPITokens()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(durableBefore, durableAfter) {
|
||||
t.Error("withdrawn caller changed the durable inventory")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// These handlers do not read a body. Capture a genuine credential admission,
|
||||
// then withdraw it before entering the transaction, as can happen while the
|
||||
// admitted request waits for configuration ownership.
|
||||
func TestSecurityTokenMutationTransactionsFollowCallerWithdrawal(t *testing.T) {
|
||||
for _, operation := range []string{"delete", "rotate"} {
|
||||
for _, change := range []string{"revoked", "hash replaced", "scope removed", "expired", "rebound", "owner changed", "invalid runtime role"} {
|
||||
t.Run(operation+"/"+change, func(t *testing.T) {
|
||||
router, cfg, caller, target := tokenWithdrawalFixture(t)
|
||||
method, path, handler := http.MethodDelete, "/api/security/tokens/"+target.ID, router.handleDeleteAPIToken
|
||||
if operation == "rotate" {
|
||||
method, path, handler = http.MethodPost, path+"/rotate", router.handleRotateAPIToken
|
||||
}
|
||||
req := httptest.NewRequest(method, path, nil)
|
||||
req.Header.Set("X-API-Token", "synthetic-withdrawal-caller.12345678")
|
||||
if !CheckAuth(cfg, httptest.NewRecorder(), req) {
|
||||
t.Fatal("original caller was not admitted")
|
||||
}
|
||||
if change == "invalid runtime role" {
|
||||
// Persistence already refuses invalid roles. Keep that valid
|
||||
// saved baseline, then exercise an in-memory authority fault.
|
||||
config.Mu.Lock()
|
||||
err := router.persistence.SaveAPITokens(cfg.APITokens)
|
||||
config.Mu.Unlock()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
config.Mu.Lock()
|
||||
wantStatus := http.StatusUnauthorized
|
||||
for i := range cfg.APITokens {
|
||||
current := &cfg.APITokens[i]
|
||||
if current.ID != caller.ID {
|
||||
continue
|
||||
}
|
||||
switch change {
|
||||
case "revoked":
|
||||
cfg.RemoveAPIToken(caller.ID)
|
||||
case "hash replaced":
|
||||
current.Hash = "different-credential-hash"
|
||||
case "scope removed":
|
||||
current.Scopes = []string{config.ScopeSettingsRead}
|
||||
wantStatus = http.StatusForbidden
|
||||
case "expired":
|
||||
expires := time.Now().Add(-time.Second)
|
||||
current.ExpiresAt = &expires
|
||||
case "rebound":
|
||||
current.OrgIDs = []string{"default", "different-estate"}
|
||||
wantStatus = http.StatusForbidden
|
||||
case "owner changed":
|
||||
current.Metadata = map[string]string{apiTokenMetadataOwnerUserID: "different-owner"}
|
||||
case "invalid runtime role":
|
||||
current.Metadata = map[string]string{"runtime_role": "unknown-role"}
|
||||
}
|
||||
break
|
||||
}
|
||||
cfg.SortAPITokens()
|
||||
var err error
|
||||
if change != "invalid runtime role" {
|
||||
err = router.persistence.SaveAPITokens(cfg.APITokens)
|
||||
}
|
||||
config.Mu.Unlock()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := tokenWithdrawalInventory(t, router)
|
||||
durableBefore, err := router.persistence.LoadAPITokens()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
logger := installTokenMutationAuditProbe(t, func() {
|
||||
if !config.Mu.TryLock() {
|
||||
t.Error("withdrawal denial retained configuration ownership during audit")
|
||||
return
|
||||
}
|
||||
config.Mu.Unlock()
|
||||
})
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
if rec.Code != wantStatus {
|
||||
t.Errorf("status=%d, want %d", rec.Code, wantStatus)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), `"token":`) {
|
||||
t.Error("withdrawn caller received a replacement secret")
|
||||
}
|
||||
if string(tokenWithdrawalInventory(t, router)) != string(before) {
|
||||
t.Error("withdrawn transaction changed live credentials")
|
||||
}
|
||||
durableAfter, err := router.persistence.LoadAPITokens()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(durableBefore, durableAfter) {
|
||||
t.Error("withdrawn transaction changed saved credentials")
|
||||
}
|
||||
events, err := logger.Query(audit.QueryFilter{})
|
||||
if err != nil || len(events) == 0 {
|
||||
t.Fatal("withdrawal denial omitted its audit result")
|
||||
}
|
||||
for _, event := range events {
|
||||
if event.Success {
|
||||
t.Error("withdrawn transaction audited a successful mutation")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityTokenMutationUsesCurrentGrantScopes(t *testing.T) {
|
||||
for _, operation := range []string{"create", "scope", "delete", "rotate"} {
|
||||
for _, allowed := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/allowed=%v", operation, allowed), func(t *testing.T) {
|
||||
router, cfg, caller, target := tokenWithdrawalFixture(t)
|
||||
method, path, body, handler := http.MethodPatch, "/api/security/tokens/"+target.ID, `{"scopes":["monitoring:read","monitoring:write"]}`, router.handleUpdateAPIToken
|
||||
if operation == "create" {
|
||||
method, path, body, handler = http.MethodPost, "/api/security/tokens", `{"name":"New collector","scopes":["monitoring:read","monitoring:write"]}`, router.handleCreateAPIToken
|
||||
}
|
||||
if operation == "delete" {
|
||||
method, body, handler = http.MethodDelete, "", router.handleDeleteAPIToken
|
||||
}
|
||||
if operation == "rotate" {
|
||||
method, path, body, handler = http.MethodPost, path+"/rotate", "", router.handleRotateAPIToken
|
||||
}
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("X-API-Token", "synthetic-withdrawal-caller.12345678")
|
||||
if !CheckAuth(cfg, httptest.NewRecorder(), req) {
|
||||
t.Fatal("original caller was not admitted")
|
||||
}
|
||||
config.Mu.Lock()
|
||||
for i := range cfg.APITokens {
|
||||
if cfg.APITokens[i].ID == caller.ID {
|
||||
cfg.APITokens[i].Scopes = []string{config.ScopeSettingsWrite}
|
||||
if allowed {
|
||||
cfg.APITokens[i].Scopes = append(cfg.APITokens[i].Scopes, config.ScopeMonitoringRead, config.ScopeMonitoringWrite)
|
||||
}
|
||||
}
|
||||
}
|
||||
cfg.SortAPITokens()
|
||||
config.Mu.Unlock()
|
||||
rec := httptest.NewRecorder()
|
||||
handler(rec, req)
|
||||
want := http.StatusForbidden
|
||||
if allowed {
|
||||
want = http.StatusOK
|
||||
if operation == "delete" {
|
||||
want = http.StatusNoContent
|
||||
}
|
||||
}
|
||||
if rec.Code != want {
|
||||
t.Errorf("status=%d, want %d", rec.Code, want)
|
||||
}
|
||||
if !allowed && strings.Contains(rec.Body.String(), `"token":`) {
|
||||
t.Error("old grant scope issued a new secret")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityTokenMutationKeepsLiveSelfWithdrawal(t *testing.T) {
|
||||
for _, operation := range []string{"delete", "rotate", "narrow"} {
|
||||
t.Run(operation, func(t *testing.T) {
|
||||
router, cfg, caller, _ := tokenWithdrawalFixture(t)
|
||||
method, path, body, want := http.MethodDelete, "/api/security/tokens/"+caller.ID, "", http.StatusNoContent
|
||||
if operation == "rotate" {
|
||||
method, path, want = http.MethodPost, path+"/rotate", http.StatusOK
|
||||
}
|
||||
if operation == "narrow" {
|
||||
method, body, want = http.MethodPatch, `{"scopes":["monitoring:read"]}`, http.StatusOK
|
||||
}
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("X-API-Token", "synthetic-withdrawal-caller.12345678")
|
||||
rec := httptest.NewRecorder()
|
||||
router.Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != want {
|
||||
t.Fatalf("live self-change status=%d, want %d", rec.Code, want)
|
||||
}
|
||||
if operation == "rotate" {
|
||||
var response struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config.Mu.RLock()
|
||||
valid := cfg.IsValidAPIToken(response.Token)
|
||||
config.Mu.RUnlock()
|
||||
if response.Token == "" || !valid {
|
||||
t.Error("self-rotation lost the replacement credential")
|
||||
}
|
||||
}
|
||||
checkReq := httptest.NewRequest(http.MethodGet, "/api/security/tokens", nil)
|
||||
checkReq.Header.Set("X-API-Token", "synthetic-withdrawal-caller.12345678")
|
||||
check := httptest.NewRecorder()
|
||||
router.Handler().ServeHTTP(check, checkReq)
|
||||
denied := http.StatusUnauthorized
|
||||
if operation == "narrow" {
|
||||
denied = http.StatusForbidden
|
||||
}
|
||||
if check.Code != denied {
|
||||
t.Errorf("old authority remains usable: status=%d, want %d", check.Code, denied)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityTokenMutationRejectsShadowedCredential(t *testing.T) {
|
||||
router, cfg, caller, target := tokenWithdrawalFixture(t)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/security/tokens/"+target.ID+"/rotate", nil)
|
||||
req.Header.Set("X-API-Token", "synthetic-withdrawal-caller.12345678")
|
||||
if !CheckAuth(cfg, httptest.NewRecorder(), req) {
|
||||
t.Fatal("original credential was not admitted")
|
||||
}
|
||||
shadow := caller.Clone()
|
||||
shadow.ID = "different-first-matching-record"
|
||||
shadow.CreatedAt = time.Now().Add(time.Hour)
|
||||
config.Mu.Lock()
|
||||
cfg.UpsertAPIToken(shadow)
|
||||
config.Mu.Unlock()
|
||||
before := tokenWithdrawalInventory(t, router)
|
||||
rec := httptest.NewRecorder()
|
||||
router.handleRotateAPIToken(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized || strings.Contains(rec.Body.String(), `"token":`) {
|
||||
t.Error("old context chose authority behind the first matching credential")
|
||||
}
|
||||
if string(tokenWithdrawalInventory(t, router)) != string(before) {
|
||||
t.Error("shadowed caller changed the inventory")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityTokenMutationSharedIssuerKeepsTenantInventoryOwner(t *testing.T) {
|
||||
for _, change := range []string{"live", "revoked", "owner removed", "owner replaced"} {
|
||||
t.Run(change, func(t *testing.T) {
|
||||
const orgID, raw = "tenant-a", "synthetic-tenant-mutation.12345678"
|
||||
record := newTokenRecord(t, raw, []string{config.ScopeSettingsWrite, config.ScopeRelayMobileAccess}, nil)
|
||||
record.OrgID = orgID
|
||||
base := newTestConfigWithTokens(t)
|
||||
tenant := &config.Config{APITokens: []config.APITokenRecord{record.Clone()}}
|
||||
persistence := config.NewMultiTenantPersistence(t.TempDir())
|
||||
if _, err := persistence.GetPersistence(orgID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
makeManager := func(cfg *config.Config) *monitoring.MultiTenantMonitor {
|
||||
t.Helper()
|
||||
manager := monitoring.NewMultiTenantMonitor(base, persistence, nil)
|
||||
// Cached owners suffice: no monitor, database, appliance or Mobile
|
||||
// runtime is started to exercise the shared credential transaction.
|
||||
owner := &monitoring.Monitor{}
|
||||
setUnexportedField(t, owner, "config", cfg)
|
||||
setUnexportedField(t, manager, "monitors", map[string]*monitoring.Monitor{orgID: owner})
|
||||
t.Cleanup(manager.Stop)
|
||||
return manager
|
||||
}
|
||||
manager := makeManager(tenant)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/security/tokens/relay-mobile", nil)
|
||||
req.Header.Set("X-Pulse-Org-ID", orgID)
|
||||
req.Header.Set("X-API-Token", raw)
|
||||
req = extractAndStoreAuthContext(base, manager, req)
|
||||
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, orgID))
|
||||
if getAPITokenRecordFromRequest(req) == nil {
|
||||
t.Fatal("tenant credential was not admitted")
|
||||
}
|
||||
liveManager := manager
|
||||
source, ok := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource)
|
||||
if !ok {
|
||||
t.Fatal("tenant credential lost its owning inventory")
|
||||
}
|
||||
source.resolveManager = func() *monitoring.MultiTenantMonitor { return liveManager }
|
||||
req = req.WithContext(context.WithValue(req.Context(), tenantTokenSourceContextKey, source))
|
||||
// Global credentials intentionally take precedence at initial auth.
|
||||
// Introduce the identical global copy only AFTER tenant admission,
|
||||
// so it tests forbidden fallback rather than bypassing this fixture.
|
||||
config.Mu.Lock()
|
||||
base.UpsertAPIToken(record)
|
||||
config.Mu.Unlock()
|
||||
switch change {
|
||||
case "revoked":
|
||||
config.Mu.Lock()
|
||||
tenant.RemoveAPIToken(record.ID)
|
||||
config.Mu.Unlock()
|
||||
case "owner removed":
|
||||
liveManager = nil
|
||||
case "owner replaced":
|
||||
liveManager = makeManager(&config.Config{})
|
||||
}
|
||||
router := &Router{config: base, persistence: config.NewConfigPersistence(base.DataPath)}
|
||||
before := tokenWithdrawalInventory(t, router)
|
||||
token, created, err := router.createAPITokenRecord(req, "Mobile access", relayMobileAccessTokenScopes(), nil, nil)
|
||||
if change == "live" {
|
||||
if err != nil || token == "" || created == nil || created.OrgID != orgID || !created.HasScope(config.ScopeRelayMobileAccess) || created.HasScope(config.ScopeSettingsWrite) {
|
||||
t.Fatal("live shared issuer lost its existing org-scoped compatibility")
|
||||
}
|
||||
} else {
|
||||
failure, ok := err.(*tokenMutationFailure)
|
||||
if !ok || failure.status != http.StatusUnauthorized || token != "" || created != nil {
|
||||
t.Error("shared issuer fell back from withdrawn tenant owner to a global copy")
|
||||
}
|
||||
if string(tokenWithdrawalInventory(t, router)) != string(before) {
|
||||
t.Error("withdrawn tenant caller changed the global inventory")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -193,14 +193,6 @@ func (r *Router) createAPITokenRecord(
|
||||
expiresIn *string,
|
||||
metadata map[string]string,
|
||||
) (string, *config.APITokenRecord, error) {
|
||||
if callerToken := getAPITokenRecordFromRequest(req); callerToken != nil {
|
||||
for _, requested := range scopes {
|
||||
if !callerToken.HasScope(requested) {
|
||||
return "", nil, fmt.Errorf("Cannot grant scope %q: your token does not have this scope", requested)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rawToken, err := internalauth.GenerateAPIToken()
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("generate raw token: %w", err)
|
||||
@@ -214,14 +206,6 @@ func (r *Router) createAPITokenRecord(
|
||||
if record.OrgID == "" {
|
||||
record.OrgID = "default"
|
||||
}
|
||||
// A full-access token in the default organization is instance-wide. A
|
||||
// caller that is not itself instance-wide must not mint one, even if it
|
||||
// holds every scope, because it would escape its own organization binding.
|
||||
if callerToken := getAPITokenRecordFromRequest(req); callerToken != nil &&
|
||||
tokenHasInstanceWideAuthority(record) && !tokenHasInstanceWideAuthority(callerToken) {
|
||||
return "", nil, fmt.Errorf("Cannot grant scope %q in the default organization: your token is not an instance-wide full-access token", config.ScopeWildcard)
|
||||
}
|
||||
setAPITokenOwnerUserID(record, apiTokenOwnerUserIDForRequest(r.config, req))
|
||||
if err := mergeAPITokenMetadata(record, metadata); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -241,6 +225,27 @@ func (r *Router) createAPITokenRecord(
|
||||
config.Mu.Lock()
|
||||
defer config.Mu.Unlock()
|
||||
|
||||
callerToken, failure := r.currentTokenMutationCallerLocked(req)
|
||||
if failure != nil {
|
||||
return "", nil, failure
|
||||
}
|
||||
if callerToken != nil {
|
||||
for _, requested := range scopes {
|
||||
if !callerToken.HasScope(requested) {
|
||||
return "", nil, fmt.Errorf("Cannot grant scope %q: your token does not have this scope", requested)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A full-access token in the default organization is instance-wide. A
|
||||
// caller that is not itself instance-wide must not mint one, even if it
|
||||
// holds every scope, because it would escape its own organization binding.
|
||||
if callerToken != nil &&
|
||||
tokenHasInstanceWideAuthority(record) && !tokenHasInstanceWideAuthority(callerToken) {
|
||||
return "", nil, fmt.Errorf("Cannot grant scope %q in the default organization: your token is not an instance-wide full-access token", config.ScopeWildcard)
|
||||
}
|
||||
setAPITokenOwnerUserID(record, apiTokenOwnerUserIDForRequest(r.config, req))
|
||||
|
||||
previousTokens := append([]config.APITokenRecord(nil), r.config.APITokens...)
|
||||
r.config.APITokens = append(r.config.APITokens, *record)
|
||||
r.config.SortAPITokens()
|
||||
@@ -424,6 +429,11 @@ func (r *Router) handleCreateAPIToken(w http.ResponseWriter, req *http.Request)
|
||||
|
||||
rawToken, record, err := r.createAPITokenRecord(req, name, scopes, payload.ExpiresIn, nil)
|
||||
if err != nil {
|
||||
if failure, ok := err.(*tokenMutationFailure); ok {
|
||||
r.auditTokenEvent(req, "token_created", false, "Caller authority changed before token creation")
|
||||
failure.write(w)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(err.Error(), "Cannot grant scope "):
|
||||
r.auditTokenEvent(req, "token_created", false, "Scope escalation denied for token creation")
|
||||
@@ -515,6 +525,14 @@ func (r *Router) handleUpdateAPIToken(w http.ResponseWriter, req *http.Request)
|
||||
// Keep validation and durable save/rollback atomic, but never retain
|
||||
// configuration ownership across audit destinations or HTTP output.
|
||||
|
||||
callerToken, failure := r.currentTokenMutationCallerLocked(req)
|
||||
if failure != nil {
|
||||
config.Mu.Unlock()
|
||||
r.auditTokenEvent(req, "token_updated", false, "Caller authority changed before token update")
|
||||
failure.write(w)
|
||||
return
|
||||
}
|
||||
|
||||
tokenIndex := -1
|
||||
for idx := range r.config.APITokens {
|
||||
if r.config.APITokens[idx].ID == tokenID {
|
||||
@@ -529,7 +547,7 @@ func (r *Router) handleUpdateAPIToken(w http.ResponseWriter, req *http.Request)
|
||||
return
|
||||
}
|
||||
|
||||
if !callerTokenMayManage(getAPITokenRecordFromRequest(req), &r.config.APITokens[tokenIndex]) {
|
||||
if !callerTokenMayManage(callerToken, &r.config.APITokens[tokenIndex]) {
|
||||
config.Mu.Unlock()
|
||||
r.auditTokenEvent(req, "token_updated", false, fmt.Sprintf("Organization boundary denied: caller cannot manage token id=%s", tokenID))
|
||||
http.Error(w, "Token not found", http.StatusNotFound)
|
||||
@@ -545,7 +563,7 @@ func (r *Router) handleUpdateAPIToken(w http.ResponseWriter, req *http.Request)
|
||||
// the requested scopes prevents widening a token beyond the caller's own
|
||||
// authority, including when editing itself.
|
||||
if payload.Scopes != nil {
|
||||
if callerToken := getAPITokenRecordFromRequest(req); callerToken != nil {
|
||||
if callerToken != nil {
|
||||
for _, scope := range oldRecord.Scopes {
|
||||
if !callerToken.HasScope(scope) {
|
||||
config.Mu.Unlock()
|
||||
@@ -643,6 +661,11 @@ func (r *Router) handleCreateRelayMobileAccessToken(w http.ResponseWriter, req *
|
||||
map[string]string{apiTokenMetadataPurpose: apiTokenPurposeRelayMobileAccess},
|
||||
)
|
||||
if err != nil {
|
||||
if failure, ok := err.(*tokenMutationFailure); ok {
|
||||
r.auditTokenEvent(req, "token_created", false, "Caller authority changed before relay token creation")
|
||||
failure.write(w)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(err.Error(), "Cannot grant scope "):
|
||||
r.auditTokenEvent(req, "token_created", false, "Relay mobile scope escalation denied")
|
||||
@@ -698,6 +721,14 @@ func (r *Router) handleDeleteAPIToken(w http.ResponseWriter, req *http.Request)
|
||||
// Keep validation and durable save/rollback atomic, but never retain
|
||||
// configuration ownership across audit destinations or HTTP output.
|
||||
|
||||
callerToken, failure := r.currentTokenMutationCallerLocked(req)
|
||||
if failure != nil {
|
||||
config.Mu.Unlock()
|
||||
r.auditTokenEvent(req, "token_deleted", false, "Caller authority changed before token deletion")
|
||||
failure.write(w)
|
||||
return
|
||||
}
|
||||
|
||||
previousTokens := append([]config.APITokenRecord(nil), r.config.APITokens...)
|
||||
removed := r.config.RemoveAPIToken(tokenID)
|
||||
if removed == nil {
|
||||
@@ -711,7 +742,7 @@ func (r *Router) handleDeleteAPIToken(w http.ResponseWriter, req *http.Request)
|
||||
// delete tokens whose scopes are a subset of their own. This prevents a
|
||||
// limited-scope token from deleting a broader token and forcing rotation or
|
||||
// lockout on a more privileged credential.
|
||||
if callerToken := getAPITokenRecordFromRequest(req); callerToken != nil {
|
||||
if callerToken != nil {
|
||||
if !callerTokenMayManage(callerToken, removed) {
|
||||
// Put the record back before returning so the in-memory config is unchanged.
|
||||
r.config.APITokens = append(r.config.APITokens, *removed)
|
||||
@@ -786,6 +817,14 @@ func (r *Router) handleRotateAPIToken(w http.ResponseWriter, req *http.Request)
|
||||
// Keep validation and durable save/rollback atomic, but never retain
|
||||
// configuration ownership across audit destinations or HTTP output.
|
||||
|
||||
callerToken, failure := r.currentTokenMutationCallerLocked(req)
|
||||
if failure != nil {
|
||||
config.Mu.Unlock()
|
||||
r.auditTokenEvent(req, "token_rotated", false, "Caller authority changed before token rotation")
|
||||
failure.write(w)
|
||||
return
|
||||
}
|
||||
|
||||
// Find existing token
|
||||
var oldRecord config.APITokenRecord
|
||||
found := false
|
||||
@@ -809,7 +848,7 @@ func (r *Router) handleRotateAPIToken(w http.ResponseWriter, req *http.Request)
|
||||
// The same applies to organizations: a caller bound to one organization
|
||||
// must not rotate, and so obtain the raw value of, another organization's
|
||||
// token.
|
||||
if callerToken := getAPITokenRecordFromRequest(req); callerToken != nil {
|
||||
if callerToken != nil {
|
||||
if !callerTokenMayManage(callerToken, &oldRecord) {
|
||||
config.Mu.Unlock()
|
||||
r.auditTokenEvent(req, "token_rotated", false,
|
||||
|
||||
@@ -384,8 +384,8 @@ func TestSecurityTokens_Create_RejectsScopeEscalationForTokenCaller(t *testing.T
|
||||
}{
|
||||
{
|
||||
name: "explicit scope escalation",
|
||||
body: `{"name":"escalated","scopes":["monitoring:read","settings:write"]}`,
|
||||
wantFragment: `Cannot grant scope "settings:write"`,
|
||||
body: `{"name":"escalated","scopes":["monitoring:read","monitoring:write"]}`,
|
||||
wantFragment: `Cannot grant scope "monitoring:write"`,
|
||||
},
|
||||
{
|
||||
name: "omitted scopes defaults to wildcard escalation",
|
||||
@@ -403,8 +403,9 @@ func TestSecurityTokens_Create_RejectsScopeEscalationForTokenCaller(t *testing.T
|
||||
persistence: persistence,
|
||||
}
|
||||
|
||||
caller := newTokenRecord(t, "limited-caller-token-123.12345678", []string{config.ScopeMonitoringRead}, nil)
|
||||
caller := newTokenRecord(t, "limited-caller-token-123.12345678", []string{config.ScopeSettingsWrite, config.ScopeMonitoringRead}, nil)
|
||||
caller.OrgID = "acme"
|
||||
cfg.UpsertAPIToken(caller)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/security/tokens", strings.NewReader(tt.body))
|
||||
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "acme"))
|
||||
@@ -418,8 +419,8 @@ func TestSecurityTokens_Create_RejectsScopeEscalationForTokenCaller(t *testing.T
|
||||
if !strings.Contains(rr.Body.String(), tt.wantFragment) {
|
||||
t.Fatalf("expected response to contain %q, got %q", tt.wantFragment, rr.Body.String())
|
||||
}
|
||||
if len(cfg.APITokens) != 0 {
|
||||
t.Fatalf("expected no tokens to be stored after denied creation, got %d", len(cfg.APITokens))
|
||||
if len(cfg.APITokens) != 1 || cfg.APITokens[0].ID != caller.ID {
|
||||
t.Fatal("denied creation changed the saved caller inventory")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -442,6 +443,7 @@ func TestSecurityTokens_Delete_RejectsScopeEscalationForTokenCaller(t *testing.T
|
||||
|
||||
caller := newTokenRecord(t, "limited-caller-token-123.12345678", []string{config.ScopeSettingsWrite}, nil)
|
||||
caller.OrgID = "default"
|
||||
cfg.UpsertAPIToken(caller)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/security/tokens/broad-token", nil)
|
||||
req = req.WithContext(authpkg.WithAPIToken(req.Context(), &caller))
|
||||
@@ -454,7 +456,7 @@ func TestSecurityTokens_Delete_RejectsScopeEscalationForTokenCaller(t *testing.T
|
||||
if !strings.Contains(rr.Body.String(), config.ScopeWildcard) {
|
||||
t.Fatalf("expected forbidden response to mention missing scope, got %q", rr.Body.String())
|
||||
}
|
||||
if len(cfg.APITokens) != 1 || cfg.APITokens[0].ID != "broad-token" {
|
||||
t.Fatalf("expected target token to remain configured, got %+v", cfg.APITokens)
|
||||
if len(cfg.APITokens) != 2 || findAPITokenByID(t, cfg.APITokens, "broad-token").Hash != "hash-broad" {
|
||||
t.Fatal("denied deletion changed the target or saved caller")
|
||||
}
|
||||
}
|
||||
@@ -74,11 +74,13 @@ func TestSecurityTokens_CreateInheritsOwnerUserIDFromTokenCaller(t *testing.T) {
|
||||
persistence: persistence,
|
||||
}
|
||||
|
||||
caller, err := config.NewAPITokenRecord("caller-token-123.12345678", "caller", []string{config.ScopeMonitoringRead})
|
||||
caller, err := config.NewAPITokenRecord("caller-token-123.12345678", "caller", []string{config.ScopeSettingsWrite, config.ScopeMonitoringRead})
|
||||
if err != nil {
|
||||
t.Fatalf("new caller token record: %v", err)
|
||||
}
|
||||
caller.Metadata = map[string]string{apiTokenMetadataOwnerUserID: "alice"}
|
||||
caller.OrgID = "acme"
|
||||
cfg.UpsertAPIToken(*caller)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/security/tokens", strings.NewReader(`{"name":"child","scopes":["monitoring:read"]}`))
|
||||
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "acme"))
|
||||
@@ -98,13 +100,14 @@ func TestSecurityTokens_CreateInheritsOwnerUserIDFromTokenCaller(t *testing.T) {
|
||||
if createResp.Record.OwnerUserID != "alice" {
|
||||
t.Fatalf("child ownerUserId = %q, want alice", createResp.Record.OwnerUserID)
|
||||
}
|
||||
if len(cfg.APITokens) != 1 {
|
||||
t.Fatalf("expected one stored token, got %d", len(cfg.APITokens))
|
||||
if len(cfg.APITokens) != 2 {
|
||||
t.Fatalf("expected parent and child, got %d stored tokens", len(cfg.APITokens))
|
||||
}
|
||||
if got := cfg.APITokens[0].Metadata[apiTokenMetadataOwnerUserID]; got != "alice" {
|
||||
child := findAPITokenByID(t, cfg.APITokens, createResp.Record.ID)
|
||||
if got := child.Metadata[apiTokenMetadataOwnerUserID]; got != "alice" {
|
||||
t.Fatalf("stored child owner_user_id = %q, want alice", got)
|
||||
}
|
||||
if got := cfg.APITokens[0].OrgID; got != "acme" {
|
||||
if got := child.OrgID; got != "acme" {
|
||||
t.Fatalf("stored child org = %q, want acme", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -126,6 +127,7 @@ func TestSecurityTokens_RotateRejectsScopeEscalation(t *testing.T) {
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/security/tokens/"+old.ID+"/rotate", nil)
|
||||
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "acme"))
|
||||
req = req.WithContext(authpkg.WithAPIToken(req.Context(), &caller))
|
||||
rec := httptest.NewRecorder()
|
||||
router.handleRotateAPIToken(rec, req)
|
||||
|
||||
Reference in new issue
Block a user