Skip to main content

Crate windows_impersonation_token_sys

Crate windows_impersonation_token_sys 

Source
Expand description

Memory-safe capture, transport, and scoped application of Windows impersonation tokens.

ImpersonationToken captures the calling thread’s effective security context into an owned impersonation token that can be carried across threads without exposing its raw handle or mutation rights.

§Capture contract

Capture is synchronous. If the calling thread is impersonating, the captured token preserves its identification, impersonation, or delegation level. If the thread has no token, capture snapshots the process identity as a SecurityImpersonation token. Windows does not permit anonymous impersonation contexts to be opened, so they are rejected as CaptureFailure::AnonymousContext.

§Application and restoration

ImpersonationToken::with_impersonation applies the captured token only for the dynamic extent of a closure. Before applying it, the method opens a handle to the exact thread-token object present on entry, or records that the thread had no token. That exact state is restored on ordinary return and during unwinding; restoration never substitutes a duplicate token and never uses RevertToSelf.

A failure to save the entry state or apply the captured token is returned as ApplyError before the closure runs. A failure to restore the entry state panics because continuing to use a shared worker thread under an unknown identity would be unsafe. If the closure is already unwinding, the resulting double panic aborts the process.

§Security invariants

  • The captured handle is owned, non-inheritable, and grants only TOKEN_IMPERSONATE.
  • Clones share the same immutable token object; no safe API exposes its handle or permits token mutation or rights expansion.
  • The private restoration guard cannot move to or be shared with another thread.
  • The public API is closure-only, so safe code cannot forget the restoration guard.

§Example

Capture once, move the owned token to a worker, and scope access-checked work to that context:

use std::thread;
use windows_impersonation_token_sys::ImpersonationToken;

let token = ImpersonationToken::capture()?;
let worker = thread::spawn(move || {
    token.with_impersonation(|| {
        // Perform access-checked Windows work here.
    })
});

worker.join().expect("worker panicked")?;

Structs§

ApplyError
A synchronous failure while applying a captured impersonation context.
CaptureError
A synchronous failure while capturing the calling thread’s effective impersonation context.
ImpersonationToken
An owned, immutable snapshot of a Windows impersonation context.

Enums§

ApplyFailure
The stage at which a captured token could not be applied.
CaptureFailure
The stage at which an impersonation context could not be captured.