Skip to main content

SecurityContext

Struct SecurityContext 

Source
pub struct SecurityContext {
Show 13 fields pub user_id: UserId, pub roles: Vec<String>, pub tenant_id: Option<TenantId>, pub scopes: Vec<String>, pub attributes: HashMap<String, Value>, pub request_id: String, pub ip_address: Option<String>, pub authenticated_at: DateTime<Utc>, pub expires_at: DateTime<Utc>, pub issuer: Option<String>, pub audience: Option<String>, pub email: Option<String>, pub display_name: Option<String>,
}
Expand description

Security context for authorization evaluation.

Carries information about the authenticated user and their permissions throughout the request lifecycle.

§Fields

  • user_id: Unique identifier for the authenticated user (from JWT ‘sub’ claim)
  • roles: User’s roles (e.g., ["admin", "moderator"], from JWT ‘roles’ claim)
  • tenant_id: Organization/tenant identifier for multi-tenant systems
  • scopes: OAuth/permission scopes (e.g., ["read:user", "write:post"])
  • attributes: Custom claims from JWT (e.g., department, region, tier)
  • request_id: Correlation ID for audit logging and tracing
  • ip_address: Client IP address for geolocation and fraud detection
  • authenticated_at: When the JWT was issued
  • expires_at: When the JWT expires
  • issuer: Token issuer for multi-issuer systems
  • audience: Token audience for validation

Fields§

§user_id: UserId

User ID (from JWT ‘sub’ claim)

§roles: Vec<String>

User’s roles (e.g., ["admin", "moderator"])

Extracted from JWT ‘roles’ claim or derived from other claims. Used for role-based access control (RBAC) decisions.

§tenant_id: Option<TenantId>

Tenant/organization ID (for multi-tenancy)

When present, RLS policies can enforce tenant isolation. Extracted from JWT ‘tenant_id’ or X-Tenant-Id header.

§scopes: Vec<String>

OAuth/permission scopes

Format: {action}:{resource} or {action}:{type}.{field} Examples:

  • read:user
  • write:post
  • read:User.email
  • admin:*

Extracted from JWT ‘scope’ claim.

§attributes: HashMap<String, Value>

Custom attributes from JWT claims

Arbitrary key-value pairs from JWT payload. Examples: “department”, “region”, “tier”, “country”

Used by custom RLS policies that need domain-specific attributes.

§request_id: String

Request correlation ID for audit trails

Extracted from X-Request-Id header or generated. Used for tracing and audit logging across services.

§ip_address: Option<String>

Client IP address

Extracted from X-Forwarded-For or connection socket. Used for geolocation and fraud detection in RLS policies.

§authenticated_at: DateTime<Utc>

When the JWT was issued

§expires_at: DateTime<Utc>

When the JWT expires

§issuer: Option<String>

Token issuer (for multi-issuer systems)

§audience: Option<String>

Token audience (for audience validation)

§email: Option<String>

Normalised email address from the JWT email claim.

Available as jwt:email in session variable mappings for RLS policies.

§display_name: Option<String>

Normalised display name from the JWT name claim.

Available as jwt:name or jwt:display_name in session variable mappings.

Implementations§

Source§

impl SecurityContext

Source

pub const ACTING_FOR_ATTRIBUTE: &'static str = "fraiseql.acting_for"

Attribute key under which the delegated user’s UUID is carried (string form), for an agent request acting on behalf of a human. Read back via acting_for (#390).

Source

pub const ACTOR_TYPE_ATTRIBUTE: &'static str = "fraiseql.actor_type"

Attribute key under which the request’s ActorType is carried (the snake_case token), derived at from_user and read back via actor_type (#390).

Source

pub const ENRICHMENT_ATTRIBUTE: &'static str = "fraiseql.enrichment"

Attribute key recording that this principal passed the enrichment seam (#1336). Absent means “no transport resolved this principal”, which is the fail-closed case the engine refuses when the schema declares an enrichment consumer — see EnrichmentMark.

Source

pub const TRACE_CONTEXT_ATTRIBUTE: &'static str = "fraiseql.trace_context"

Attribute key under which the originating request’s full W3C trace context is carried (a JSON object), used to populate the change-log trace_context JSONB column (#375).

Source

pub const TRACE_ID_ATTRIBUTE: &'static str = "fraiseql.trace_id"

Attribute key under which the originating request’s W3C trace id is stamped. Set by the server’s request pipeline from the inbound traceparent header; read back via trace_id.

Source

pub const TRANSPORT_ATTRIBUTE: &'static str = "fraiseql.transport"

Attribute key under which the ingress transport is carried (#376): the door this request came through, e.g. "mcp". Set by a transport that declares itself (via with_transport) — never from a client field: the fraiseql. namespace is stripped from token claims by the extractor, so a caller cannot forge it. Recorded into the change-log row’s extra_metadata.transport.

Source

pub fn from_user(user: &AuthenticatedUser, request_id: String) -> Self

Create a security context from an authenticated user and request metadata.

§Arguments
  • user - Authenticated user from JWT validation
  • request_id - Correlation ID for this request
§Example
// Requires: a live AuthenticatedUser from JWT validation.
// See: tests/integration/ for runnable examples.
let context = SecurityContext::from_user(&authenticated_user, "req-123".to_string());
Source

pub fn system_job( job_id: impl Into<String>, request_id: impl Into<String>, roles: Vec<String>, scopes: Vec<String>, tenant: Option<TenantId>, ) -> Self

Construct the context for an internal scheduled / system job (#573 D6).

Unlike from_user, this carries no JWT and no request — it is the server acting as itself for background work: a scheduled Source, and (in future) after:ingest handlers and saga steps. It is the first and, at introduction, only construction of ActorType::SystemJob.

Its authority is exactly the roles + scopes the caller grants (the source’s run_as ceiling). With neither, it is fail-closed: no roles and no scopes mean every RBAC / field-authz check denies and — with no tenant — tenant-scoped RLS admits nothing. A source therefore cannot write until an operator grants it a ceiling.

tenant scopes writes for a single-tenant or global source (None = global / NULL tenant); a multi-tenant source leaves it None and re-scopes each write per message via with_tenant. job_id names the job (the source name) and becomes the system_job:<id> principal for the audit envelope; request_id correlates a single firing.

The ActorType is recorded for audit, never an authorization input — the authority comes solely from roles/scopes.

Source

pub fn service_account( name: impl Into<String>, request_id: impl Into<String>, roles: Vec<String>, scopes: Vec<String>, tenant: Option<TenantId>, ) -> Self

Mint a service-account context from a run_as ceiling (ADR-0018).

A service account is an external credentialed caller — a daemon or service authenticated by a static secret — as opposed to an internal system_job firing. Authority is exactly the run_as ceiling (roles/scopes/tenant); an absent/empty ceiling ⇒ no authority (RLS and field-authz deny its writes). The identity is service_account:<name> and the ActorType is ServiceAccount — recorded for audit (tb_entity_change_log.actor_type), never an authorization input.

Source

pub fn has_role(&self, role: &str) -> bool

Check if the user has a specific role.

§Arguments
  • role - Role name to check (e.g., “admin”, “moderator”)
§Returns

true if the user has the specified role, false otherwise.

Source

pub fn has_scope(&self, scope: &str) -> bool

Check if the user has a specific scope.

Supports wildcards: admin:* matches any admin scope.

§Arguments
  • scope - Scope to check (e.g., “read:user”, “write:post”)
§Returns

true if the user has the specified scope, false otherwise.

Source

pub fn get_attribute(&self, key: &str) -> Option<&Value>

Get a custom attribute from the JWT claims.

§Arguments
  • key - Attribute name
§Returns

The attribute value if present, None otherwise.

Source

pub fn trace_id(&self) -> Option<&str>

The originating request’s W3C trace id, when the server stamped one from the inbound traceparent header.

Used to populate the change-log trace_id column so an outbox row links back to its distributed trace (#375); the #392 perf tooling surfaces it as the investigation handle. None when the request carried no trace context.

Source

pub fn with_trace_id(self, trace_id: impl Into<String>) -> Self

Stamp the originating request’s W3C trace id onto the context (carried in attributes). Read back via trace_id.

Source

pub fn trace_context(&self) -> Option<&Value>

The originating request’s full W3C trace context (a JSON object), when the server stamped one from the inbound traceparent/tracestate headers.

Used to populate the change-log trace_context JSONB column so an outbox row carries enough to re-propagate the distributed trace (#375). None when the request carried no valid trace context.

Source

pub fn with_trace_context(self, trace_context: Value) -> Self

Stamp the originating request’s full W3C trace context (a JSON object) onto the context (carried in attributes). Read back via trace_context.

Source

pub fn actor_type(&self) -> ActorType

The request’s actor classification (#390). Derived at from_user; ActorType::HumanUser when unset (e.g. a context built directly without derivation).

Source

pub fn with_actor_type(self, actor_type: ActorType) -> Self

Stamp the request’s ActorType onto the context (carried in attributes). Read back via actor_type.

Source

pub fn acting_for(&self) -> Option<Uuid>

The delegated user (the human a delegated agent acts for), when the request carried an RFC 8693 act claim (#390). None for a non-delegated request, or when the underlying subject was not UUID-shaped.

Source

pub fn with_acting_for(self, acting_for: Option<Uuid>) -> Self

Stamp the delegated user’s UUID onto the context (carried in attributes). None removes any prior stamp. Read back via acting_for.

Source

pub fn transport(&self) -> Option<&str>

The ingress transport this request declared (#376), e.g. "mcp". None for transports that do not stamp one (today: everything except MCP), and for contexts built without a server pipeline.

Source

pub fn with_transport(self, transport: &str) -> Self

Stamp the ingress transport onto the context (carried in attributes, forge-safe: the extractor strips the fraiseql. namespace from token claims). Read back via transport and recorded into the change-log’s extra_metadata.transport by the mutation runner.

Source

pub fn enrichment_mark(&self) -> Option<EnrichmentMark>

How this principal satisfied the enrichment requirement (#1336), or None when it never passed the seam.

None is the fail-closed state, and it is the default precisely because the defect this guards against is a transport that builds a principal and dispatches it without resolving. A context that skipped the seam cannot claim to have passed it by saying nothing.

Source

pub fn mark_enrichment(&mut self, mark: EnrichmentMark)

Record that this principal passed the enrichment seam.

Carried in attributes under the reserved fraiseql. namespace, which the token-claim builder strips — so a caller cannot mint this mark from a JWT claim. Only server code on the request path sets it.

Source

pub fn is_expired(&self) -> bool

Check if the token has expired.

§Returns

true if the JWT has expired, false otherwise.

Source

pub fn ttl_secs(&self) -> i64

Get time until expiry in seconds.

§Returns

Seconds until JWT expiry, negative if already expired.

Source

pub fn is_admin(&self) -> bool

Check if the user is an admin.

§Returns

true if the user has the “admin” role, false otherwise.

Source

pub const fn is_multi_tenant(&self) -> bool

Check if the context has a tenant ID (multi-tenancy enabled).

§Returns

true if tenant_id is present, false otherwise.

Source

pub fn with_role(self, role: String) -> Self

Set or override a role (for testing or runtime role modification).

Source

pub fn with_scopes(self, scopes: Vec<String>) -> Self

Set or override scopes (for testing or runtime permission modification).

Source

pub fn with_tenant(self, tenant_id: impl Into<TenantId>) -> Self

Set tenant ID (for multi-tenancy).

Source

pub fn with_attribute(self, key: String, value: Value) -> Self

Set a custom attribute (for testing or runtime attribute addition).

Source

pub fn jwt_claim(&self, claim: &str, tenant_claim: &str) -> Option<Value>

The value of JWT claim claim for this request.

The one answer to “what is claim X” (#1388). Inject parameters (jwt:<claim>), session variables (source = "jwt") and identity-enrichment bindings all read claims through this, so a claim name means the same thing on every path. Three copies used to answer differently, and two of them answered both tenant_id and org_id with Self::tenant_id whatever the schema’s tenant claim was, so a token carrying both scoped a query by the wrong one.

Resolution, first match wins:

  1. the raw claim, from Self::attributes (every non-reserved claim lands there);
  2. a registered claim the validator lifts out of the claim map into its own field, so it never reaches attributes: sub (also spelled user_id) → Self::user_id, email → Self::email, name (also display_name) → Self::display_name, iss → Self::issuer, scope → Self::scopes as the space-separated string an OAuth token carries (#1417; absent when no scope is granted);
  3. tenant_claim — the schema’s configured tenant claim, and only that name — → Self::tenant_id.

Step 3 is what lets a principal the server mints itself (a service account, a system job, a source’s per-message tenant, an admin preview) answer row-mode tenancy’s jwt:<tenant_claim> with the tenant it was assigned. For a principal built from a token it changes nothing: its tenant is that claim’s value (see the server’s context builder), so step 1 already answered. No other name reads the tenant.

Source

pub fn can_access_scope( &self, security_config: &SecurityConfig, required_scope: &str, ) -> bool

Check if user can access a field based on role definitions.

Takes a required scope and checks if any of the user’s roles grant that scope.

§Arguments
  • security_config - Security config from compiled schema with role definitions
  • required_scope - Scope required to access the field (e.g., “read:User.email”)
§Returns

true if the user’s roles grant the required scope, false otherwise.

§default_role

A principal carrying no role at all falls back to SecurityConfig::default_role (#894). The condition is an empty role set, not a failed lookup: a principal that has been assigned roles has been given its authority, and quietly widening it when those roles fall short would make default_role a floor under every principal rather than a default.

The fallback reaches authenticated principals only, because a SecurityContext exists only for one — an anonymous request has no principal and is classified by apply_anonymous_field_rbac_filtering, which never calls this method. That is deliberate: extending the fallback to anonymous callers would re-open #743’s privilege inversion from the other side, handing every requires_scope field to callers who presented no credential.

§Example
// Requires: a SecurityConfig from a compiled schema.
// See: tests/integration/ for runnable examples.
let can_access = context.can_access_scope(&config, "read:User.email");

Trait Implementations§

Source§

impl Clone for SecurityContext

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SecurityContext

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for SecurityContext

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for SecurityContext

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Serialize for SecurityContext

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more