gnomonlearn
Docs/Hosting/RFC-0048

RFC-0048 · Principal and Session Model

Versioned draft snapshot

RFCs, reference catalogs, and evidence reflect Spec 3b2e3e7a114fb826b1445d39a48756b8fff629cd. Counts and pending/status notes belong to that snapshot. Read the dated project update for later progress.

Source repositories are private during staging. Links marked “repository access required” need access to the linked repository.

Status Draft corpus. Reference catalogs and RDF projections have generation drift checks; Gnomon proofs and projection semantics remain unverified for release.

View the generated reference catalog →

Read design questions and decisions →


Reference catalog: the diagnostics, linked-RFC graph, defined terms, and normative-rule index for this RFC are in the reference catalog, generated from the structured Lean module. This document carries the prose: design rationale, entity-shape definitions in context, and migration notes.


1. Purpose

This RFC defines who the caller is in a Gnomon runtime: how identity flows from an inbound request through authorization, into operation handlers, and out to audit. It specifies the Principal type, the Session type, the authentication flow that resolves an inbound request to a Principal, the session lifecycle (bootstrap → authenticate → maintain → refresh → expire), capability attenuation (extending RFC-0010 §8.2’s object-capability model with session-level restrictions), and the contract that any session token format must satisfy.

This RFC defines the first-release contract for the principal-service, authentication-service, and jwt-service DI tokens in gnomon/modules/modules/core.auth/module.gnm. Existing source is conformance input; nothing is deployed to migrate.


2. Definitions

TermMeaning
PrincipalThe stable identity of a caller. A user, a service account, an internal system component, or the special “anonymous” identity.
SessionA bound runtime context: a Principal + tenant + capabilities + timing + scope. The unit of authentication state.
AuthenticationThe process that resolves an inbound request’s credentials to a Principal.
AuthorizationThe process that checks whether a Principal’s Session permits a specific operation. (Defined in RFC-0042; this RFC supplies the Principal/Session inputs.)
Capability attenuationThe narrowing of a Principal’s full capability set to the subset permitted by the current Session.
Session tokenAn opaque or signed string that lets a caller resume a previously-authenticated Session across requests.
Anonymous principalThe well-known Principal representing unauthenticated calls.

3. Principal

3.1 Shape

Principal {
  id:           Text                  // stable, opaque identifier
  kind:         Text                  // "user", "service", "system", "anonymous"
  displayName:  Text | null
  attributes:   Map<String, Any>      // arbitrary structured metadata
  tenantId:     Text | null           // home tenant; null for cross-tenant or anonymous
  scopes:       List<Text>            // capability scope names declared on this Principal
  createdAt:    Instant
  isActive:     Boolean
}

3.2 Identity

id is opaque to the runtime. It is typically:

  • A UUID for user accounts.
  • A namespaced service identifier for service accounts (service.<name>).
  • A reserved value system.installer for the system installer principal (RFC-0041 §11.1).
  • The literal anonymous for the anonymous principal (§3.5).

Implementations MAY index or correlate principals by id; the runtime MUST NOT impose a structural format on it.

3.3 Kind

kind classifies the principal for audit and policy purposes:

KindMeaning
userA human user account
serviceA service-to-service account, often headless
systemAn internal Gnomon runtime principal (e.g., system.installer)
anonymousThe unauthenticated caller

The system kind is reserved; user code MUST NOT create system principals. Attempts to do so produce M48010.

3.4 Attributes and scopes

attributes is a structured map for principal-specific metadata: email, organization affiliation, roles, group memberships, etc. The runtime does NOT prescribe attribute keys; modules and authentication backends declare the attributes they need.

scopes is a list of capability scope names (RFC-0040 §5.1.1: root, core, app, admin, webhook, the kernel-owned public scope, plus any custom scopes registered by modules). A principal’s scope list is the set of capability scopes the principal MAY operate within.

The actual capability set granted to any specific session is bounded by the principal’s scopes via attenuation (§5.3).

3.5 The anonymous principal

The runtime defines a single, well-known anonymous principal:

Principal {
  id:           "anonymous"
  kind:         "anonymous"
  displayName:  "Anonymous"
  attributes:   {}
  tenantId:     null
  scopes:       [public]
  isActive:     true
}

The public scope is kernel-owned. Anonymous principals MUST have only this scope. APIs that permit anonymous access (RFC-0033 §6.3 auth.required: false) MUST explicitly publish a read-only, non-tenant operation to public; a missing grant is denied. The compiler and runtime MUST reject any public grant to a mutating or tenant-scoped operation. There is no ambient anonymous bypass.

3.6 Persistence

Principals are persisted as Resources of kind core.identity.user (or core.identity.service, etc.) in the graph backend. Their data blob carries the structured attributes; their externalId is the principal id.

The mapping from Resource to Principal is performed by the principal service (legacy principal-service):

PrincipalService {
  byId(id: Text): Promise<Principal | null>
  byCredential(credential: Credential): Promise<Principal | null>
  attributes(id: Text): Promise<Map<String, Any>>
}

4. Session

4.1 Shape

Session {
  id:                  Text                  // unique session identifier
  principalId:         Text                  // ID of the bound principal
  tenantId:            Text | null           // active tenant for this session
  scopes:              List<Text>            // attenuated scope set (subset of principal.scopes)
  issuedAt:            Instant
  expiresAt:           Instant
  refreshableUntil:    Instant | null
  parentSessionId:     Text | null           // for derived/sub-sessions
  authMethod:          Text                  // how this session was authenticated
  attributes:          Map<String, Any>      // session-scoped state
}

4.2 Lifecycle

A session moves through five phases:

1. Bootstrap     — request arrives; runtime checks for an existing session token
2. Authenticate  — resolve credentials → Principal; create new session
3. Maintain      — session is active; capabilities resolved per-request from session.scopes
4. Refresh       — extend expiresAt without re-authenticating; bounded by refreshableUntil
5. Expire        — session ends; subsequent requests with the token MUST be rejected

Each phase is documented below (§7).

4.3 Scope attenuation at session creation

When a session is created (phase 2), its scopes MUST be a subset of the bound principal’s scopes (§3.4). The session MAY further narrow scopes based on:

  • The authentication method (authMethod): some methods (e.g., webhook) restrict to a specific scope subset.
  • The API surface: a webhook-classified API surface (RFC-0033) creates sessions with scopes: [webhook].
  • The caller’s request: a request MAY ask for a narrower session via the protocol (e.g., OAuth scope=read).

The session scope MUST be recorded at creation; it MUST NOT be widened during the session’s lifetime.

4.4 Tenant binding

tenantId is the active tenant for the session. In single-tenant mode (GNOMON_TENANT_MODE=single), authenticated sessions carry the runtime’s single tenant. Request-only public sessions are the exception: their tenantId is null and they cannot access tenant-scoped operations. In multi-tenant mode, an authenticated session is bound to one tenant at creation; cross-tenant session escalation is prohibited (M48020).

A new session for a different tenant requires a new authentication; the old session does NOT carry over.

4.5 Sub-sessions

Operations that invoke other operations may create derived sub-sessions with further-narrowed scopes (§5.3). A sub-session’s:

  • parentSessionId references the originating session.
  • scopes MUST be a subset of the parent’s scopes.
  • expiresAt MUST NOT exceed the parent’s expiresAt.

Sub-sessions support the principle of least privilege: a long-running operation can spawn a narrowly-scoped sub-session for a single internal call.


5. Capability Attenuation

5.1 Relationship to RFC-0010 §8.2

RFC-0010 §8.2 defines an object-capability model: capability tokens authorize specific operations. This RFC adds a session layer: every capability resolution MUST be filtered through the active session.

The composition is:

effective_capabilities(operation, session) =
  capabilities_declared_by_operation ∩ expand(session.scopes)

expand resolves scope names to the capabilities they authorize. Unknown scopes resolve to the empty set. If the capability intersection is empty, the operation is denied (M48030). The root scope expands to its declared capability closure; it is not compared as a literal string to narrower scope names.

5.2 Capability scope filtering

The runtime filters capabilities by the session’s scopes:

Session scopeCapabilities resolvable
rootAll capabilities, including admin and platform
corePlatform-level capabilities; cannot resolve app-restricted user-data capabilities
appApplication-level capabilities post-auth
adminAdmin operations (must also have admin claim)
webhookSingle-shot, narrow capabilities for webhook callbacks
publicExplicitly published read-only, non-tenant capabilities for anonymous callers

The webhook scope is intentionally minimal: it permits the specific operations the webhook subscription declared, nothing else.

5.3 Sub-session attenuation

When an operation invokes another operation internally, the runtime creates a derived sub-session (§4.5). It first resolves scope names to capability sets, intersects the parent’s actual capabilities with those required by the called operation, and mints only references in that intersection. The resulting sub-session’s authority MUST be a subset of the parent’s authority; it cannot gain capabilities through a different scope spelling.

Example: an app-scoped session invokes an internal saga step requiring a core capability. If the parent’s expanded capabilities do not include it, the child receives no such capability and the read fails. A root session invoking a core-only step receives only the required core capabilities. A separate service principal requires its own authentication and authorization; it is not an implicit elevation of the parent session.

5.4 Attenuation is final

Once attenuated, a session’s scopes cannot be widened. There is no API for “elevate to higher scope” without a fresh authentication. This is the foundation of capability discipline: the session always holds the most permissive set it will ever have.


6. Authentication

6.1 Authentication contract

Authentication backends fulfill the legacy authentication-service token. The contract:

AuthenticationService {
  authenticate(credential: Credential): Promise<Unsupported | Rejected | Authenticated>
  refresh(token: Text): Promise<{ session: Session, replacementToken?: Text }>
  invalidate(sessionId: Text): Promise<void>
  resolve(token: Text): Promise<Session | null>
}

Credential is a discriminated-union of supported credential forms:

KindCarrier
bearer-token{ kind: "bearer-token", token: Text }
api-key{ kind: "api-key", key: Text }
basic{ kind: "basic", username, password }
mutual-tls{ kind: "mutual-tls", certPem: Text }
webhook-signature{ kind: "webhook-signature", body, signature, ... }
internal{ kind: "internal", parentSession: Session, derivedScopes: List<Text> }

Backends MAY support a subset of the credential kinds. Unsupported means this authenticator does not handle the credential kind; dispatch MAY try the next authenticator. Rejected means a recognized credential failed validation and dispatch MUST stop without anonymous fallback. Authenticated carries the Session and any replacement credential. If no authenticator handles a credential, the runtime emits M48040. Existing auth/session interchange already uses a schema layer; changes there MUST remain schema-validated.

6.2 Auth method recording

The session’s authMethod field records how authentication was achieved. Standard values: bearer-token, api-key, basic, mutual-tls, webhook-signature, internal-call, system-bootstrap. This field is normative and audited (RFC-0047 §3).

6.3 Pluggable authenticators

RFC-0040/0041 select one AuthenticationService provider for the runtime token; its lifecycle is singleton. That service MAY register multiple credential-specific strategies in declaration order. Only Unsupported continues the strategy chain; Rejected stops it; the first Authenticated result wins. A malformed credential is rejected, even when the target API permits anonymous access. An override of the service provider follows RFC-0041 provider-selection rules and does not silently append a strategy to the old provider.

6.4 Anonymous authentication

The runtime synthesizes an anonymous session for any inbound request that arrives without credentials AND targets an API surface where auth.required: false (RFC-0033 §6.3). The synthesized session has:

Session {
  id:           "anon.<correlation-id>"
  principalId:  "anonymous"
  tenantId:     null
  scopes:       [public]
  authMethod:   "anonymous"
  ...
}

Anonymous sessions are not persisted. They live only for the duration of the request and can resolve only explicitly published public capabilities.


7. Session Lifecycle

7.1 Bootstrap

When a request arrives, the runtime extracts a session token from the protocol (Authorization: Bearer <token> for HTTP, equivalent for others). If a token is present:

  • The token-format adapter validates its format and, when applicable, signature.
  • The runtime calls AuthenticationService.resolve(token) to fetch the bound Session.
  • If the Session is found and not expired, it becomes the active session.

If no token is present and the API permits anonymous access, an anonymous session is synthesized (§6.4). A present but invalid token is rejected; it MUST NOT fall back to anonymous access. A tokenless request to a non-public API is rejected (M48050).

7.2 Authenticate (new session)

When a new session is needed (e.g., login), the runtime calls AuthenticationService.authenticate(credential). On success:

  • A new Session is created with the bound Principal.
  • A session token is issued (§8).
  • Authoritative session state or a revocation index is stored in the session backing store (typically a Resource of kind core.identity.session, RFC-0036 §6.1 conventions).

7.3 Maintain

During the active phase, every request observes:

  • The session’s expiresAt is in the future.
  • The session’s principalId resolves to an active Principal (isActive: true).
  • The session’s tenantId matches the request’s claimed tenant.
  • The authoritative session record has not been invalidated or superseded by token rotation.

If any check fails, the session is rejected and the runtime returns core.errors.Unauthorized.

7.4 Refresh

A session MAY be refreshed via AuthenticationService.refresh(token), extending expiresAt to a new value and returning the Session plus an optional replacement token. Refreshes are bounded by refreshableUntil: once that time passes, the session cannot be refreshed and the user must re-authenticate. When rotation is selected, the old token is invalidated atomically with the new token’s issuance.

Refresh MUST NOT widen scopes (§5.4).

7.5 Expire / invalidate

A session expires when:

  • expiresAt passes (passive expiration).
  • AuthenticationService.invalidate(sessionId) is called (active invalidation, e.g., logout).
  • The bound Principal is deactivated (isActive: false) — propagates as session expiration on next check.

Expired sessions MUST be rejected with core.errors.Unauthorized. Subsequent attempts to refresh an expired session MUST produce M48060.


8. Session Token

8.1 Token contract

This RFC does NOT pick a specific session token format (JWT, opaque, ULID-keyed, etc.). It specifies the contract any token format MUST satisfy:

  1. Resolvable — the token can be exchanged for a Session via AuthenticationService.resolve(token).
  2. Tamper-resistant — modification of the token MUST be detectable. Either the token is signed (JWT, signed envelope) or it’s an opaque server-side reference.
  3. Bounded lifetime — the token’s lifetime is bounded by the session’s expiresAt.
  4. Replay-safe in expected window — tokens within the expiry window MAY be replayed by the legitimate caller; the contract permits idempotent usage. The token alone is NOT proof of single-use; operation idempotency (RFC-0043 §6) addresses repeated mutations, while transport and credential safeguards address bearer-token theft.

8.2 Storage

The first release requires an authoritative session store or revocation index consulted on every privileged request. The AuthenticationService owns it. Supported token representations include:

  • JWT-style — the token carries signed session claims, but its session ID or token version is checked against authoritative state. Signing-key rotation is not a substitute for per-session logout.
  • Opaque-server-token — the token is a key into a session table; the server holds the full session record.
  • Hybrid — short-lived JWTs paired with a refresh token resolved server-side.

The token representation is a deployment choice; the revocation and active-principal checks are not optional.

8.3 Token rotation

Session tokens MAY rotate on refresh: refresh(old) returns a Session and a replacement token, and the old token is invalidated atomically. Rotation is implementation-optional; nonrotating tokens still use authoritative state for expiry, invalidation, and principal activity.

8.4 Tokens MUST NOT be principal IDs

A common pitfall: using a stable, recoverable principal id (e.g., user UUID) as the session token. This RFC prohibits it. Tokens are session handles, not principal handles. Principal id MAY appear inside a signed token’s payload but MUST NOT be the token itself.


9. Identity Flow

9.1 Inbound request

Request → Protocol Server → Bootstrap Session → Auth Check (api.auth) →
Operation Handler (with services.principal, services.session injected)

The protocol server (RFC-0034) extracts the credential, calls authentication, and attaches the resulting Session to the request context. Operation handlers access:

  • services.principal: Principal — the Principal bound to the session.
  • services.session: Session — the active session.
  • services.tenant: Text | null — the tenant id.

9.2 Outbound (client) calls

When an operation invokes a client operation (RFC-0024), the runtime MAY:

  • Pass the session’s identity through (X-Forwarded-Principal header equivalent).
  • Use the session’s credentials to call the external service (when the client is configured for delegated auth).
  • Use a service principal (when the client is configured for service-to-service auth).

The choice is per-client configuration.

9.3 Audit

Every operation invocation records principalId, tenantId, and the verified authMethod in the audit log (RFC-0047 §3.1). The audit log is the primary trail for “who did what, when.”


10. Invariants

  1. The anonymous principal has the stable ID anonymous across runtime restarts and only the kernel-owned public scope (§3.5).
  2. system kind principals MUST NOT be user-created (§3.3, M48010).
  3. Session scopes MUST be a subset of the bound principal’s scopes (§4.3).
  4. Session scopes MUST NOT be widened during the session’s lifetime (§5.4).
  5. Cross-tenant session escalation is prohibited (§4.4, M48020).
  6. Sub-session capabilities are the intersection of resolved parent capabilities and called-operation requirements (§5.3).
  7. Anonymous sessions are not persisted; they live only for the request (§6.4).
  8. Session tokens MUST NOT be the same as principal IDs (§8.4).
  9. Refresh MUST NOT widen scopes; it only extends expiresAt (§7.4).
  10. The audit log MUST record principalId, tenantId, and authMethod for every operation (§9.3, RFC-0047 §3.1).

11. Compatibility and Migration

11.1 Existing source contracts

The legacy module manifest at /Volumes/Workspace/savvi-studio-full/modules/src/core.auth/module.gnm declares four DI tokens:

Legacy tokenThis RFC
principal-service§3.6 PrincipalService contract
authentication-service§6.1 AuthenticationService contract
authorization-serviceRFC-0042 (consumed by this RFC)
jwt-service§8 (one specific implementation of the token contract)

These tokens exist in source. Their implementations require conformance review against this first-release session contract; their presence does not prove behavior.

11.2 First-release requirements

  • Sessions MUST record authMethod (§6.2). Legacy code does not.
  • Sub-session attenuation is normative (§5.3). Legacy code may permit broader propagation.
  • Cross-tenant escalation is prohibited (§4.4). Legacy code is permissive in some paths.

Nothing is deployed, so no session or token migration is required.

11.3 The bootstrap principal

The runtime image (RFC-0045) MUST seed the system.installer Principal during boot, before any module install runs (RFC-0041 §11.1). This principal has scopes [root] and is the creator of all bootstrap state. User code MUST NOT use this principal at runtime (M48010).


Diagnostics

The diagnostic catalog for this RFC is authored in the structured Lean module and rendered in reference catalog § Diagnostics. Inline mentions in the prose above (e.g., “rejected with MNNxxx”) cross-link to the catalog at render time.

Linked References

The cross-RFC dependency graph is rendered in reference catalog § Linked References. Out-of-KG pointers to legacy code or external resources, when present, remain in this document under “Source-tree references” below.