Skip to main content

EnvelopeContext

Struct EnvelopeContext 

Source
pub struct EnvelopeContext {
    pub request_id: u64,
    pub cnf: [u8; 32],
    /* private fields */
}
Expand description

Context extracted from a verified SignedEnvelope.

Passed to service handlers after signature verification. Handlers use this for:

  • Authorization checks via subject()
  • Correlation via request_id

§Example

ⓘ
fn handle_request(&self, ctx: &EnvelopeContext, payload: &[u8]) -> Result<(Vec<u8>, Option<Continuation>)> {
    // Check authorization
    let sub = ctx.subject().to_string();
    if !policy_manager.check(&sub, "Model", "infer") {
        return Err(anyhow!("unauthorized: {}", sub));
    }
    // Process request...
}

Fields§

§request_id: u64

Unique request ID for correlation and logging

§cnf: [u8; 32]

Ed25519 public key of the envelope signer (RFC 7800 confirmation key). Cryptographically verified by Ed25519 signature check.

Implementations§

Source§

impl EnvelopeContext

Source

pub fn from_mediated_evidence( evidence: &[u8], mediator_service: &str, operation: &str, ) -> Result<EnvelopeContext, Error>

Verify the original holder’s hybrid transcript without granting local transport provenance. Credential verification is still mandatory.

Source

pub fn original_holder_evidence(&self) -> Option<&[u8]>

Bounded original signed request for a read-only mediated Policy query. Possession of these bytes is not an identity grant; the receiver must independently verify holder, credential, target, method and freshness.

Source

pub fn admit_mediated_query( &self, mediator: &str, resource: &str, operation: &str, ) -> Result<(), Error>

Record a verified holder’s derived authorization query, independently of the request’s original dispatch admission. No default local store: startup must install the topology-qualified replay backend.

Source

pub fn from_verified_as_system(envelope: &SignedEnvelope) -> EnvelopeContext

Create context for a FixedSigner (inproc/IPC) caller.

Sets key_derived_subject = Subject::new("system"), so subject() always returns "system" for this context regardless of any caller-asserted authorization field. Used in process_request for inproc callers.

Source

pub fn from_callback_service( request_id: u64, service_name: &str, ) -> EnvelopeContext

Create a service-identity context for internal callbacks that bypass the envelope pipeline.

Used by services that make inproc self-calls without a real SignedEnvelope (e.g., InferenceService callback mode). Sets key_derived_subject = "service:{name}" so that subject() returns a proper service identity for authorization.

cnf is zeroed because there is no real envelope; the service subject is asserted directly and is trusted because this constructor is only reachable from internal code paths that never cross a network boundary.

Source

pub fn ensure_browser_method( &self, actual_method_discriminator: u16, ) -> Result<(), Error>

Compare the sealed client method commitment with the discriminator independently decoded by generated service dispatch. Legacy carriers have no commitment; browser dispatch always installs one.

Source

pub fn subject(&self) -> Subject

Get the cryptographically-verified authorization subject.

Resolution order:

  1. Key-derived subject (from verified Ed25519 signer key via KeyRegistry). For FixedSigner/inproc callers this is always Subject::new("system").
  2. JWT upgrade: if the envelope carries a verified JWT token, use its subject. Federated JWTs (iss non-empty) produce Subject::federated(iss, sub).
  3. Subject::anonymous() — no verified identity.

The caller-asserted envelope authorization is not preserved in the context — only verified state is available to handlers.

Source

pub fn domain(&self) -> Result<String, Error>

Derive the Casbin request domain from the verified tenant binding.

For network callers this comes only from a JWT after verify_claims() verifies its signature and issuer. Trusted in-process constructors bind their callers to the local tenant. The subject name is deliberately not a fallback: multiple subjects may share a tenant, and identities without a tenant binding must fail closed.

Source

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

Return the authority-verified tenant binding, if the request has one.

Callers must still use Self::domain before treating this value as a Casbin domain: that accessor rejects empty and wildcard tenant claims. This optional view lets cross-tenant authorities distinguish a missing tenant (where an authenticated service principal may use the global policy domain) from a present-but-invalid tenant (which must fail closed).

Source

pub fn user(&self) -> &str

Get the bare username string.

Source

pub fn is_authenticated(&self) -> bool

Check if the identity is authenticated (not anonymous).

Source

pub fn authenticated_signer_key(&self) -> Option<VerifyingKey>

Return the verified Ed25519 signer key for this authenticated request.

This is the authentication-bound key material for the subject returned by Self::subject. For JWT callers, verify_claims() requires the JWT confirmation key to match cnf before the context reaches a handler. For key-resolved callers, the subject is resolved from this same verified key. Callback contexts have no envelope signer and are deliberately refused.

Source

pub fn authenticated_pairwise_did(&self) -> Option<Did>

Return this request’s self-certifying pairwise DID.

This is deliberately distinct from Self::subject. The latter is a Casbin-facing authorization label (for example "alice" or "https://issuer:alice"); it is not a decentralized identifier and must never be relabelled as one. The pairwise DID is derived only from the Ed25519 key whose possession the verified envelope established. Callback contexts and anonymous requests have no such identity.

Source

pub fn authenticated_pq_signer_key(&self) -> Option<VerifyingKey<MlDsa65>>

Return the trusted PQ key anchored to this request’s verified signer.

A missing binding is represented as None because Classical transport authentication is a valid, lower-assurance state; the returned key is never taken from request data.

Source

pub fn claims(&self) -> Option<&Claims>

Get user claims (if present, after verify_claims has run).

Source

pub fn verified_key_material(&self) -> VerifiedKeyMaterial

Derive the verified key material (S8/#574, S1/#548). This is the accessor that threads crypto-derived assurance from the envelope’s verified signature into MAC context assembly.

Returns the [VerifiedKeyMaterial] assurance axis for THIS verified envelope, derived (never trusted) from what the signature layer actually verified:

  • PqHybrid — the envelope’s cnf Ed25519 signer key is cryptographically verified (it is self.cnf, set during Self::from_verified from the signature check) AND a bound ML-DSA-65 anchor for that identity is present in the global PqTrustStore (register_pq_trust binding) under the enforced Hybrid policy. This is the kid-anchored binding the rest of the TCB uses — the PQ key is resolved from the trust store keyed by the EdDSA identity, never self-asserted. A session-overlay binding also reaches PqHybrid, but only when it has been confirmed out of band; a first-contact binding is capped at Classical by crate::session_pq_overlay::PqProvenance::key_material.
  • Classical — the cnf Ed25519 signer key is verified but NO bound ML-DSA-65 anchor is present (the federation edge, or a pre-PQ identity), or the only binding is a first-contact one, which makes the signature checkable without making the signer more trusted.
  • Unverified — the cnf key is zeroed (a callback-service context with no real envelope; assurance floors to the S1 Unverified floor so it dominates nothing above it).

Re-derive per verified envelope; never cache across identities. Each envelope has its own signer; caching would conflate assurances.

This is the load-bearing S8 input: without it every subject floors to Unverified and dominates nothing (S6 would deny everything). The MAC PDP combines this with the clearance off Claims via crate::auth::mac::SubjectContextClaims::security_context.

Source

pub fn security_context(&self) -> Option<SecurityContext>

Derive the full MAC [SecurityContext] for this verified envelope: the two-input S1 derivation (clearance from Claims + assurance from Self::verified_key_material). This is the convenience entry-point the MAC PDP / S6 grant path call; it composes the authority-asserted clearance with the crypto-derived assurance, clamping the assurance axis DOWN to what the verified key supports.

Returns None (→ S1 deny) when the subject carries no clearance (unlabeled subject) — there is no default clearance. The resulting context is a SIBLING to Subject: identity and clearance are independent dimensions of the same verified principal.

Re-derive per verified envelope; never cache across identities.

Source

pub fn is_federate_tui_class(&self) -> bool

Get the effective verified JWT token from the envelope.

For an authorized relay this is the delegated bearer, allowing a downstream service to preserve the original user’s verified identity across another local service boundary. Whether the verified credential is of the Federate TUI client class (set by verify_claims; never caller-supplied).

Source

pub fn is_delegated_bearer(&self) -> bool

Whether this request’s identity came from a delegated bearer token (an authenticated service mediator presented the holder’s token).

Source

pub fn has_delegated_resource_audience(&self) -> bool

Source

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

Source

pub fn verified_direct_jwt(&self) -> Option<(&Claims, &str)>

A direct network credential only after the full verifier returned successfully. Never substitutes a relayed bearer, legacy claims, local callback identity, or a partially checked JWT. The returned claims remain evidence, not a dispatch permit.

Source

pub fn deferred_federate_credential(&self) -> Option<(&Claims, &str)>

Signature-verified reserved credential awaiting dynamic holder proof, current session and Policy request-use admission. This is evidence only; subject(), domain() and claims() remain unpublished meanwhile.

Source

pub fn request_proof_cwt(&self) -> Option<&[u8]>

Original verified-envelope proof bytes, still untrusted until the appropriate signer-suite verifier authenticates them.

Source

pub fn admitted_federate_operation( &self, resource: &str, operation: &str, ) -> bool

Exact request-local Policy-use coordinate, never a reusable permit. A serving handler must compare every generated authorization call with this tuple and perform its ordinary fresh Policy check as well.

Source

pub fn is_federate_admitted(&self) -> bool

Source

pub fn has_user_context(&self) -> bool

Check if request has user context

Source

pub fn internal_work(&self) -> Option<&InternalWorkContext>

The verified internal execution work order, when this request crossed a pinned single-service execution boundary (Model → its Inference subprocessor). None for every direct caller; a service MUST treat its presence as “the controller already authorized this exact operation” — never as bearer delegation.

Source

pub fn ephemeral_pubkey(&self) -> Option<[u8; 32]>

Get the client’s ephemeral DH public key (if present). Used by streaming handlers to derive shared secrets for HMAC chain keys.

Source

pub fn stream_kem_recipient(&self) -> Option<&RecipientPublic>

Get the authenticated identified-stream HyKEM recipient.

Source

pub fn response_kem_recipient(&self) -> Option<&RecipientPublic>

The one-shot unary reply recipient authenticated by the envelope. Deferred Federate admission additionally requires the original holder proof to bind this value before any handler or authority side effect.

Source

pub fn is_local_caller(&self) -> bool

Whether this request came from a genuine in-process / IPC caller (#328).

true for the FixedSigner mutual-auth plane and internal self-calls; false for networked / mesh peers (AnySigner). Used to confine the empty-iss JWT shortcut to local callers.

Source

pub fn audit_authz(&self, resource: &str, operation: &str, allowed: bool)

Emit an accounting / audit record for an authorization decision (#445).

This is the Accounting leg of AAA: it makes every authorization decision attributable after the fact to the cryptographically verified subject (self.subject()), never a caller-asserted field. It is called by generated dispatch code at the authorization decision point — the single DRY chokepoint where the verified subject, the resource, the operation, and the allow/deny effect are all in scope.

The record is a structured tracing event on the dedicated audit target so it can be filtered/routed independently (e.g. shipped to an audit sink) without coupling to the rest of the daemon’s logs. Fields: subject, resource, action, decision (allow/deny), and request_id for correlation. It records only identity + resource + action + decision — never key material or request payloads.

Allow is logged at info; deny at warn (deny is the security-relevant event), but both carry identical structured fields so “who did what” is reconstructable for the allow path AND the deny path.

S7 (#573, #453): this is the control-plane (Casbin #[authorize]) audit surface. The data-plane MAC surface (the AVC) emits its own records on the same unified hyprstream.mac.audit target via hyprstream::mac::audit. Both targets fan out to OpenTelemetry when the otel feature is active (OTel is a tracing subscriber), so denials are first-class observable signals — closing the #453 visibility gap where auth failures were previously buried at debug level. We also mirror the decision onto hyprstream.mac.audit here so a single OTel subscriber captures the whole authorization audit stream.

Trait Implementations§

Source§

impl Clone for EnvelopeContext

Source§

fn clone(&self) -> EnvelopeContext

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 EnvelopeContext

Source§

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

Formats the value using the given formatter. 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
§

impl<T> Any for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

§

fn type_name(&self) -> &'static str

§

impl<T> AnySync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send> ⓘ

§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

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

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

§

const WITNESS: W = W::MAKE

A constant of the type witness
§

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

§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
§

impl<T> Instrument for T

§

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

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

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<T> JaggedSlice<T> for T

§

type Index = Index2

§

fn push_into(self, array: &mut Jagged<T>)

§

fn insert_into(self, index: <T as JaggedSlice<T>>::Index, array: &mut Jagged<T>)

§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

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

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: 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
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: 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
§

impl<T> ServiceExt for T

§

fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>
where Self: Sized,

Apply a transformation to the response body. Read more
§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
§

fn follow_redirects(self) -> FollowRedirect<Self>
where Self: Sized,

Follow redirect resposes using the Standard policy. Read more
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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<T> ErasedDestructor for T
where T: 'static,

§

impl<T> MaybeSend for T
where T: Send,

§

impl<T> MaybeSend for T
where T: Send,

§

impl<T> MaybeSync for T
where T: Sync,

§

impl<T> MaybeSync for T
where T: Sync,

§

impl<E> ResultError for E
where E: Send + Debug + Sync,

§

impl<T> ResultType for T
where T: Send + Clone + Sync + Debug,

§

impl<T> SendSyncUnwindSafe for T
where T: Send + Sync + UnwindSafe + ?Sized,

Source§

impl<T> TerminalState for T
where T: Clone + Send + Sync,