spiffe 0.19.0

Core SPIFFE identity types, Workload API sources, and experimental Broker API bindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
# spiffe

[![Crates.io](https://img.shields.io/crates/v/spiffe.svg)](https://crates.io/crates/spiffe)
[![Docs.rs](https://docs.rs/spiffe/badge.svg)](https://docs.rs/spiffe/)
[![Safety](https://img.shields.io/badge/unsafe-forbidden-success.svg)](https://github.com/rust-secure-code/safety-dance)
[![Rust 1.88+](https://img.shields.io/badge/rust-1.88+-orange.svg)](https://www.rust-lang.org)

Core SPIFFE identity types and Workload API sources.

This crate provides SPIFFE identity primitives (`SpiffeId`, `TrustDomain`) and clients for the
SPIFFE Workload API (`X509Source`, `JwtSource`, `WorkloadApiClient`). It handles X.509 and JWT
SVIDs, trust bundles, and streaming updates. All cryptography and TLS integration are intentionally delegated to other crates.

---

## Installation

Add `spiffe` to your `Cargo.toml`. All features are opt-in:

```toml
[dependencies]
# Minimal: only SPIFFE primitives 
spiffe = "0.19"

# OR X.509 workloads (recommended)
# spiffe = { version = "0.19", features = ["x509-source"] }

# OR JWT workloads (recommended)
# spiffe = { version = "0.19", features = ["jwt-source"] }

# OR Direct Workload API usage
# spiffe = { version = "0.19", features = ["workload-api"] }
```

---

## Quick start

### Create a Workload API client

Using an explicit socket path:

```rust
use spiffe::WorkloadApiClient;

let client = WorkloadApiClient::connect_to(
    "unix:/tmp/spire-agent/public/api.sock",
).await?;
```

Or via the `SPIFFE_ENDPOINT_SOCKET` environment variable:

```rust
use spiffe::WorkloadApiClient;

let client = WorkloadApiClient::connect_env().await?;
```

Successful RPC responses are checked for mandatory protocol fields before
returning material. SVID lists and standalone bundle maps must be nonempty,
and every SVID entry must include its required wire metadata and material.
SVID fetches parse every returned entry, including entries after the selected
default. Missing fields return `WorkloadApiError::MissingRequiredField` with
the protobuf field path; malformed material retains its parsing error.
Certificate and JWT payloads remain the source of the parsed identity; no new
wire/payload identity equality check is applied. Optional hints, CRLs, and
federation data may be absent. Complete updates still remove omitted federation
trust, and present empty authority bundles retain their existing behavior.

---

## X.509 identities

The Workload API client exposes low-level access to X.509 materials.

```rust
use spiffe::{TrustDomain, X509Context};

let context: X509Context = client.fetch_x509_context().await?;

let trust_domain = TrustDomain::new("example.org")?;
let bundle = context
    .bundle_set()
    .get(&trust_domain)
    .ok_or("missing bundle")?;
```

### Watch for updates

Streaming examples use `futures-util`; add
`futures-util = { version = "0.3", default-features = false, features = ["std"] }`
to your dependencies.

```rust
use futures_util::StreamExt;

let mut stream = client.stream_x509_contexts().await?;

while let Some(update) = stream.next().await {
    let context = update?;
    // react to updated SVIDs and bundles
}
```

---

## `X509Source` (recommended)

`X509Source` is a higher-level abstraction built on top of the Workload API.

It maintains a locally cached, automatically refreshed view of X.509 SVIDs and bundles,
handling reconnections and rotations transparently.

```rust
use spiffe::{BundleSource, TrustDomain, X509Source};

let source = X509Source::new().await?;

// Snapshot of current materials
let context = source.x509_context()?;

// Selected SVID (default or picker)
let svid = source.svid()?;

// Bundle for a trust domain
let trust_domain = TrustDomain::new("example.org")?;
let bundle = source
    .bundle_for_trust_domain(&trust_domain)?
    .ok_or("missing bundle")?;
```

A valid complete response replaces the trust view even if the configured picker
cannot select an SVID or the selected SVID is expired. Identity acquisition then
returns `NoSuitableSvid`; it never falls back to an old or default identity.
`source.state()` obtains one immutable revision containing the matching identity
and context, its withdrawal reason, and terminal status. Reacquire the state for
current authorization.

`PermissionDenied` and `NoIdentityIssued` on the monitored material RPC withdraw
its cached material until a valid complete response reauthorizes it. A
byte-identical recovery response notifies consumers. EOF, `Unavailable`, reconnect,
and rejected malformed/over-limit updates retain previously accepted permission.
Shutdown is terminal and distinct from withdrawal. Already acquired `Arc`
credentials remain owned by their callers.

For most X.509-based workloads, `X509Source` provides a higher-level API.

---

## `JwtSource` (recommended)

`JwtSource` is a higher-level abstraction built on top of the Workload API for JWT workloads.

It maintains a locally cached, automatically refreshed view of JWT bundles,
handling reconnections and rotations transparently. JWT SVIDs are fetched on-demand
with specific audiences.
Permission denial on its bundle stream withdraws JWT bundles with the same
recovery contract. An independently denied JWT issuance request does not withdraw
bundles or X.509 material, and issuance success cannot restore withdrawn bundles.


```rust
use spiffe::{BundleSource, TrustDomain, JwtSource};

let source = JwtSource::new().await?;

// Fetch JWT SVID for specific audiences
let jwt_svid = source.fetch_jwt_svid(&["service-a", "service-b"]).await?;

// Fetch JWT SVID for a specific SPIFFE ID
let spiffe_id = "spiffe://example.org/my-service".parse()?;
let jwt_svid = source.fetch_jwt_svid_with_id(&["audience"], Some(&spiffe_id)).await?;

// Bundle for a trust domain
let trust_domain = TrustDomain::new("example.org")?;
let bundle = source
    .bundle_for_trust_domain(&trust_domain)?
    .ok_or("missing bundle")?;
```

For most JWT-based workloads, `JwtSource` provides a higher-level API.

---

## SVID hints

When multiple SVIDs are returned by the Workload API, SPIRE may attach an
**operator-defined hint** (for example, `internal` or `external`) to guide selection.

Hints are **not part of the cryptographic identity**. They are metadata
returned by the Workload API and are exposed by this crate for convenience.

* X.509 hints are attached to `X509Svid`
* JWT hints are attached to `JwtSvid`

Higher-level abstractions like `X509Source` preserve hints and allow custom
selection logic via `SvidPicker`.

---

## JWT identities

### Using `JwtSource` (recommended)

For most JWT workloads, use `JwtSource` which provides automatic bundle caching and on-demand SVID fetching:

```rust
use spiffe::JwtSource;

let source = JwtSource::new().await?;

// Fetch JWT SVID
let jwt_svid = source.fetch_jwt_svid(&["audience1", "audience2"]).await?;
```

See the [`JwtSource`](#jwtsource-recommended) section above for more details.

### Direct Workload API access

For direct access without caching, use the Workload API client:

```rust
use spiffe::{SpiffeId, WorkloadApiClient};

let client = WorkloadApiClient::connect_env().await?;

let spiffe_id = SpiffeId::try_from("spiffe://example.org/my-service")?;

let jwt = client
    .fetch_jwt_svid(&["audience1", "audience2"], Some(&spiffe_id))
    .await?;
```

### Fetch and watch JWT bundles

```rust
use futures_util::StreamExt;
use spiffe::TrustDomain;
use spiffe::WorkloadApiClient;

let client = WorkloadApiClient::connect_env().await?;

let bundles = client.fetch_jwt_bundles().await?;
let trust_domain = TrustDomain::try_from("example.org")?;
let bundle = bundles.get(&trust_domain);

let mut stream = client.stream_jwt_bundles().await?;
while let Some(update) = stream.next().await {
    let bundles = update?;
    // react to updated JWT authorities
}
```

---

## JWT verification modes

This crate supports **three distinct JWT-SVID usage patterns**, depending on where
verification happens.

### 1. Trusted by construction (no verification)

JWT-SVIDs **fetched directly from the SPIFFE Workload API** are trusted by construction.
The SPIRE agent already authenticated the workload and issued the token.

```rust
use spiffe::JwtSvid;

let svid = JwtSvid::from_workload_api_token(token_str)?;
```

Requires the `jwt` feature; no JWT verification backend is required.

---

### 2. Validation via the Workload API (recommended when available)

The Workload API exposes a validation RPC.
`WorkloadApiClient::validate_jwt_token` delegates verification to the SPIRE agent
and returns a parsed `JwtSvid`.

```rust
use spiffe::WorkloadApiClient;

let client = WorkloadApiClient::connect_env().await?;

let svid = client
    .validate_jwt_token("my-audience", jwt_token)
    .await?;
```

Characteristics:

* Signature verification is performed **by the SPIRE agent**
* No local cryptography required
* **Does not require any JWT verification feature**
* Recommended whenever the Workload API is reachable

The client also checks the successful response's required wire identity and
claims structure. The SPIFFE `sub`, `aud`, and `exp` claims must be present;
`sub` must be a SPIFFE ID, `aud` a string or nonempty string array, and `exp`
a finite number. Absent fields return `MissingRequiredField`; malformed claim
values return `InvalidResponseField`, without including response values in the
error. Other claims may be omitted or empty. These are response structure checks;
the agent remains responsible for signatures, audience matching and validity
times. The returned `JwtSvid` is still parsed from the supplied token.

---

### 3. Offline verification (explicit backend selection required)

If you need to validate **untrusted JWTs** locally (for example, tokens received
over the network), enable offline JWT verification with an explicit cryptographic
backend.

#### Using the pure-Rust backend (portable, recommended)

```toml
[dependencies]
spiffe = { version = "0.19", features = ["jwt-verify-rust-crypto"] }
```

#### Using the AWS-LC backend

```toml
[dependencies]
spiffe = { version = "0.19", features = ["jwt-verify-aws-lc-rs"] }
```

This enables local signature verification using JWT authorities from bundles:

```rust
use spiffe::JwtSvid;

let svid = JwtSvid::parse_and_validate(
    token_str,
    &bundle_source,
    &["expected-audience"],
)?;
```

Use this mode when:

* The Workload API is not available
* Tokens are received from external peers
* Fully offline validation is required

---

## Source initialization

Both source builders synchronize before returning. A fixed `.endpoint(...)` URI
is parsed once during `build()`; invalid syntax or unsupported schemes return
`Source(WorkloadApiError::Endpoint(_))` before any connection attempt. Valid TCP
endpoints with absent services and Unix endpoints with absent sockets still retry.
Use a URI such as `unix:/tmp/spire-agent/public/api.sock`, rather than a bare path.

During initial synchronization, `UNIMPLEMENTED` from `FetchX509SVID` or
`FetchJWTBundles` returns the source-specific `UnsupportedRpc` error. It identifies
the method and retains the original gRPC error, including its status code and
cause. This applies to headers and stream trailers before the first accepted
item, including a subsequent startup attempt. `INVALID_ARGUMENT` retains its
existing immediate-failure policy. Correct the endpoint or server/profile
configuration and build a new source after either terminal failure.

`Unavailable`, connection/HTTP2 failures, `DeadlineExceeded`, `PermissionDenied`,
`NoIdentityIssued`, `Unauthenticated`, `Internal`, `Unknown`, and `Cancelled` remain
retriable. Rejected malformed/over-limit responses retain their existing rejection
and retry contract. No retry-count limit or mandatory deadline is introduced;
`initial_sync_timeout(...)` continues to bound recoverable startup failures.
Custom factory errors and environment-based discovery retain their existing
retry behavior; repeated identical errors alone do not establish permanence.

After successful synchronization, `UNIMPLEMENTED` continues to reconnect with
backoff. It does not withdraw authorized material, restore withdrawn material,
advance a material revision, or close the source. Source health still describes
material usability and supervisor liveness, rather than RPC reachability. A server
upgrade can therefore recover without rebuilding a running source. TLS source
closure policies and established connection lifetimes are unchanged.

See [Workload API startup policy](../docs/workload-api-startup.md) for the full
classification and recovery contract.

## Source shutdown

`X509Source` and `JwtSource` keep join ownership independently of shutdown callers.
The first poll of a shutdown method closes admission and requests cancellation;
dropping that future leaves the request in effect. Concurrent or repeated callers
wait for actual supervisor completion, including destruction of directly owned work.

`shutdown()` waits indefinitely. `shutdown_with_timeout(duration)` gives each caller
a graceful deadline, then requests abort and joins before returning `ShutdownTimeout`.
Another caller whose deadline has not expired can return `Ok(())` after the same
completion. `shutdown_configured()` uses the builder setting, which defaults to
30 seconds; `None` waits indefinitely. A graceful deadline cannot preempt blocking
synchronous callbacks or destructors, so the final join can exceed that duration.

Dropping the last public source handle requests cancellation and abort without
blocking. A remaining clone keeps the source alive. The supervisor's termination
guard also closes getters and update subscriptions if the task is destroyed before
its first poll, while preserving the final authoritative material revision.

These guarantees cover the source supervisor. Dependency-owned transport workers,
already admitted caller-owned JWT fetches, and established TLS connections have
their own lifetimes. Custom client factories must support future abandonment and
avoid synchronous blocking.

## Features

All features are additive and opt-in. The crate has **no default features** (`default = []`).

### Core features

#### `x509`

Enables X.509 SVID and bundle types plus parsing. Gates X.509 dependencies (`x509-parser`, `pkcs8`, `zeroize`).

**Note:** Most users should enable `x509-source` instead, which includes this feature automatically.

#### `transport`

Lightweight endpoint parsing and normalization. No runtime dependencies (pure parsing logic).

#### `transport-grpc`

gRPC connector for Unix/TCP endpoints. Requires `transport` and adds tokio/tonic/tower dependencies.

#### `workload-api`

Enables the async SPIFFE Workload API client. Includes `workload-api-x509` and `workload-api-jwt` (and their `x509` and `jwt` parsing features).

Provides:

* `WorkloadApiClient` and streaming APIs
* X.509 and JWT SVID and bundle retrieval
* Streaming watch semantics
* Agent-side JWT validation (`validate_jwt_token`)

#### `x509-source`

High-level X.509 watcher and caching abstraction. Includes `workload-api-x509` (and transitively `x509`).

Provides:

* `X509Source` for automatic SVID/bundle watching and caching
* Automatic reconnection and rotation handling
* Recommended for most X.509-based workloads

#### `jwt-source`

High-level JWT watcher and caching abstraction. Includes `workload-api-jwt` (and transitively `jwt`).

Provides:

* `JwtSource` for automatic bundle watching and caching
* On-demand JWT SVID fetching with audience specification
* Automatic reconnection and rotation handling
* Recommended for most JWT-based workloads

#### `jwt`

Enables JWT SVID and bundle types plus parsing. Gates JWT-related dependencies (`serde`, `serde_json`, `time`,
`base64ct`).

**Note:** JWT verification requires an additional backend feature (see below).

---

### JWT verification backends

#### `jwt-verify-rust-crypto`

Enables **offline JWT-SVID verification** using a **pure Rust cryptography backend**.

* Portable and dependency-light
* Recommended default for offline verification
* Required only when validating untrusted JWTs locally

When enabled, [`JwtSvid::parse_and_validate`] performs JWT-SVID validation:

- **Signature verification** using keys from the trust domain's JWT bundle
- **`exp` claim**: requires `now < exp`; equality is expired
- **`nbf` claim**: optional; when present, requires `now >= nbf`
- **JOSE headers**: only `alg`, required `kid`, and optional string `typ`
  (`JWT` or `JOSE`); null `typ`, duplicates, and all extra fields reject
- **`aud` claim**: must intersect the `expected_audience` parameter
  (empty audience arrays are rejected)
- **`sub` claim**: must be present and parse as a valid SPIFFE ID
- **`kid` header**: must be present and match a key in the bundle
- **Trusted JWK metadata**: explicit `alg` must match the token; EC curve labels
  and coordinate widths must match ES256/P-256 or ES384/P-384. Explicit `use`
  must be `sig` or `jwt-svid`. Explicit `key_ops` must be a non-null array of
  distinct strings that includes `verify`, and must not declare known encryption
  or derivation operations alongside an explicit signature purpose.
- **RSA authorities**: `n` and `e` must use canonical unpadded Base64urlUInt
  encoding without leading zero octets; the actual modulus must have at least
  2048 significant bits, as required by [RFC 7518]https://www.rfc-editor.org/rfc/rfc7518.html#section-3.3.

Optional JWK `alg`, `use`, and `key_ops` may be omitted for purpose-selected JWT
bundles. Additional operations, including unknown extension operations, remain
supported when `verify` is present; they do not grant additional verification
permissions. Without explicit RSA `alg`, a key may verify multiple supported
RSA algorithms. This does not provide the complete single-algorithm-per-key
binding required by [RFC 8725](https://www.rfc-editor.org/rfc/rfc8725.html#section-3.1);
provision explicit trusted `alg` metadata to constrain it.

These checks run after exact subject-domain and `kid` selection. Failure does
not try another authority. `JwtAuthority` and `JwtBundle` parsing/storage remain
flexible, retain unknown JWK extensions, and preserve last-entry replacement
for duplicate key IDs. Duplicate JSON members still normalize to their last
value. Full SPIFFE bundles must still be filtered for JWT purposes before
being passed to the purpose-specific JWKS parser.

Temporal checks share one `SystemTime` observation at nanosecond precision with
zero clock skew. `exp` remains required integer seconds. A present `nbf` must be
a JSON number exactly representable as nanoseconds in years -9999 through 9999
(-377705116800 through 253402300799.999999999 Unix seconds). Negative dates,
decimals, and exponent notation are supported; nonzero sub-nanosecond precision,
exponents outside the signed 32-bit range, and out-of-range values reject safely.
A pre-epoch or out-of-range verification clock fails closed.

`iat` and `iss` remain unchecked, and additional private payload claims remain
permitted. These header and temporal policies apply only to offline verification;
`parse_insecure`, `FromStr`, and Workload API token parsing retain their behavior.
See [`JwtSvid::parse_and_validate`] for complete details.

```rust
use spiffe::{BundleSource, JwtBundle, JwtSvid};

fn validate_token<B: BundleSource<Item = JwtBundle>>(
    token: &str,
    bundles: &B,
) -> Result<JwtSvid, spiffe::JwtSvidError> {
    JwtSvid::parse_and_validate(token, bundles, &["my-service"])
}
```

---

### `jwt-verify-aws-lc-rs`

Enables **offline JWT-SVID verification** using **AWS-LC** via `aws-lc-rs`.

* Alternative cryptography backend
* Mutually exclusive with `jwt-verify-rust-crypto`

Header, temporal, audience, and trust-domain policies are the same as
`jwt-verify-rust-crypto`. Both backends enforce the same trusted JWK metadata,
EC curve, canonical RSA encoding, and 2048-bit minimum policies. Cryptographic
key validity and capacity limits remain backend-specific: with the locked
dependencies, RustCrypto accepts RSA moduli up to 4096 bits and AWS-LC up to
8192 bits. A valid 5120-bit authority is therefore accepted by AWS-LC and
rejected by RustCrypto. No shared maximum is imposed. ES512 remains unavailable
for offline verification with either backend.

---

### Observability features

The crate supports optional observability through two mutually compatible features:
`logging` and `tracing`. Both features are optional and can be enabled independently
or together.

#### Feature precedence

When multiple observability features are enabled, the following precedence applies:

1. **`tracing`** (highest priority) — If enabled, all events are emitted via `tracing`
2. **`logging`** — If `tracing` is not enabled, events are emitted via the `log` crate
3. **No observability** — If neither feature is enabled, observability calls are no-ops

#### `logging`

Enables observability using the [`log`](https://crates.io/crates/log) crate.

This is a lightweight option suitable for applications that use the standard `log`
facade. Events are emitted via `log::debug!`, `log::info!`, `log::warn!`, and `log::error!`.

```toml
[dependencies]
spiffe = { version = "0.19", features = ["logging"] }
```

**Note:** The `logging` feature is not included in the default `workload-api` feature.
You must explicitly enable it if you want log output.

#### `tracing`

Enables structured observability using the [`tracing`](https://crates.io/crates/tracing) crate.

This is recommended for production environments that use structured logs, spans,
or distributed tracing systems. When both `tracing` and `logging` features are enabled,
**`tracing` takes precedence** and all events are emitted via `tracing` macros.

```toml
[dependencies]
spiffe = { version = "0.19", features = ["tracing"] }
```

**Note:** The `tracing` and `logging` features are not mutually exclusive. When both
features are enabled, events are emitted via `tracing`.

---

### Workload API core (advanced)

In addition to the higher-level bundles (`workload-api-x509`, `workload-api-jwt`,
`workload-api`), the crate exposes a lower-level
`workload-api-core` feature:

```toml
[dependencies]
spiffe = { version = "0.19", features = ["workload-api-core"] }
```

This feature includes:

- **Transport layer** (`transport-grpc`): endpoint parsing and gRPC connector
- **Runtime dependencies**: `tokio`, `tonic`, `tokio-util`
- **Protobuf types**: generated Workload API message definitions

**Excluded** (not included in `workload-api-core`):

- X.509 parsing (`x509` feature)
- JWT parsing (`jwt` feature)
- High-level client methods that require parsed SVIDs/bundles

Use `workload-api-core` if you want to build a custom client or integrate with
alternative SVID/bundle representations while reusing the transport layer.

---

### Experimental features

#### `broker-api`

Bindings for the [SPIFFE Broker API](https://github.com/spiffe/spiffe/blob/main/standards/SPIFFE_Broker_API.md), which a broker uses to get SVIDs and bundles on behalf of the workloads it serves.

Provides:

* The generated `spiffe.broker` client and messages (`broker_api::pb::spiffe::broker`)
* `Debug` output for the SVID messages that shows only the length of private keys and JWT tokens
* A `SecurityHeader` interceptor that adds the required `broker.spiffe.io` security header after any custom per-request metadata
* `From` conversions that build a `WorkloadReference` from a PID or Kubernetes object reference

The Broker Endpoint requires mutual TLS, so the generated client has no plaintext `connect` and the caller builds the gRPC channel. The channel must also check the provider's SPIFFE ID.

`broker-api` is experimental and may change in a semver-incompatible release. While `spiffe` remains pre-1.0, breaking changes require a minor version bump; patch releases remain compatible.

---

### Notes on JWT verification features

* Each backend feature (`jwt-verify-rust-crypto`, `jwt-verify-aws-lc-rs`) is self-contained and automatically includes
  the `jwt` feature
* Exactly **one** offline verification backend must be selected (mutually exclusive)
* Offline verification features are **not required** when using `WorkloadApiClient::validate_jwt_token`
* X.509-based functionality is unaffected by JWT verification features

---

## Performance

Performance characteristics:

- **Zero-copy parsing** where possible (X.509 DER, JWT parsing)
- **Atomic updates** in `X509Source` and `JwtSource` (no locks on read path)
- **Streaming APIs** for real-time updates without polling
- **Minimal allocations** in hot paths

The `X509Source` and `JwtSource` maintain cached views of SVIDs and bundles, updating atomically when the Workload API delivers new
material. This eliminates the need for polling and ensures new handshakes always use the latest credentials.

---

## Architecture

The crate is organized into several layers:

1. **Core primitives** (`SpiffeId`, `TrustDomain`) — Always available, no dependencies
2. **Transport layer** (`transport`, `transport-grpc`) — Endpoint parsing and gRPC connectivity
3. **Workload API client** (`workload-api-*`) — Low-level client for SPIFFE Workload API
4. **High-level abstractions** (`x509-source`, `jwt-source`) — Automatic caching and rotation handling

This layered design allows you to use only what you need, minimizing dependencies and compile times.

---

## Troubleshooting

### Common Issues

#### "Workload API connection failed"

- **Cause**: SPIRE agent not running or socket path incorrect
- **Solution**: Verify `SPIFFE_ENDPOINT_SOCKET` environment variable or socket path

#### "Empty response from Workload API"

- **Cause**: Workload not registered with SPIRE agent
- **Solution**: Ensure your workload is properly attested and registered

---

## Security Best Practices

- **Always validate JWT tokens** when received from untrusted sources (use `jwt-verify-*` features)
- **Use `X509Source` or `JwtSource`** for automatic rotation instead of manual polling
- **Enable observability** (`logging` or `tracing`) in production for monitoring

For security vulnerabilities, see [SECURITY.md](../SECURITY.md).

### Dependency advisories (cargo audit)

This project runs `cargo audit` in CI. Some advisories may appear only when enabling optional features
(e.g., offline JWT verification). At the time of writing, `cargo audit` may report `RUSTSEC-2023-0071`
(the `rsa` crate “Marvin Attack” advisory) via `jsonwebtoken`, and there is currently no fixed upgrade
available upstream.

If you require a clean audit, avoid enabling offline JWT verification unless needed, or temporarily ignore
the advisory until upstream releases a fix.

## License

Licensed under the Apache License, Version 2.0.
See [LICENSE](LICENSE) for details.