coapum 0.2.0

A modern, ergonomic CoAP (Constrained Application Protocol) library for Rust with support for DTLS, observers, and asynchronous handlers
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
# CoAPum Feature Roadmap

This document outlines the feasibility and implementation plans for extending CoAPum to support advanced CoAP features that would enable management frontends and firmware update capabilities.

## Overview

CoAPum currently provides a solid foundation for CoAP device communication with:
- ✅ Device state management via REST-like endpoints
- ✅ Real-time updates using CoAP observe pattern  
- ✅ External state updates through `StateUpdateHandle`
- ✅ Persistent storage with Sled database
- ✅ DTLS security with PSK authentication

For management frontends and firmware updates, several key features are missing:

## Missing Features Analysis

### Critical for Management Frontends
- **No HTTP/WebSocket API**: Pure CoAP server - frontends typically need WebSocket/REST APIs
-**No Firmware Update Protocol**: No built-in firmware transfer/update mechanism
-**No Streaming Data API**: CoAP observe is limited compared to WebSocket streams
-**No Authentication/Authorization**: Beyond basic DTLS PSK, no user/role management
-**No Admin API**: No dedicated management endpoints for device provisioning, monitoring

### Low-Level Protocol Gaps
- **Block-wise Transfer** (RFC 7959): Essential for large payloads
-**Resource Directory** (RFC 9176): Dynamic device discovery/management
-**Multicast Support**: Bulk operations and device discovery
-**Link Format Parser** (RFC 6690): Structured resource discovery
-**PATCH Method Support** (RFC 8132): Efficient partial updates
-**Event Streaming Interface**: Bridge CoAP events to WebSocket streams

## Implementation Roadmap

### 1. Block-wise Transfer (RFC 7959) - **HIGH FEASIBILITY**

**Priority:** High (Essential for firmware updates)  
**Estimated Effort:** 3-4 weeks  
**Complexity:** Medium

**Implementation Approach:**
- Add `Block1Option` and `Block2Option` structs to handle block parameters (NUM, M, SZX)
- Extend router to maintain block transfer state per client/request
- Create `BlockwiseHandler` trait for streaming large payloads
- Modify response generation to support chunked responses

**Integration Points:**
- `src/serve.rs:270-300`: Add block option parsing after CoAP request parsing
- `src/router/mod.rs`: Add block state tracking to router
- `src/extract/`: New `BlockwisePayload<T>` extractor for receiving large uploads

**Key Challenges:**
- Managing server-side state for untrusted sources (security concern)
- Handling dynamic resource changes during transfer
- Ensuring atomic transfers for PUT/POST requests
- ETag consistency across blocks

---

### 2. Resource Directory (RFC 9176) - **MEDIUM FEASIBILITY**

**Priority:** High (Device management foundation)  
**Estimated Effort:** 4-6 weeks  
**Complexity:** High

**Implementation Approach:**
- Create `ResourceDirectory` struct managing endpoint registrations
- Add `.well-known/core` and `/rd*` routes to router
- Implement link format parser for registration payloads
- Add lifetime management with background cleanup tasks

**Integration Points:**
- New `src/rd/` module with registration storage (using existing Sled backend)
- `src/router/mod.rs`: Add built-in RD routes via `with_resource_directory()`
- Leverage existing observer infrastructure for registration expiry

**Key Features:**
- Endpoint registration/deregistration
- Resource lookup with filtering
- Soft-state registrations with lifetime management
- Support for sectors (logical groupings)
- Pagination of lookup results

---

### 3. Multicast Support - **HIGH FEASIBILITY**

**Priority:** Medium (Bulk operations)  
**Estimated Effort:** 2-3 weeks  
**Complexity:** Low-Medium

**Implementation Approach:**
- Add UDP multicast socket binding in `serve.rs`
- Create `MulticastConfig` for join/leave operations
- Handle multicast responses with rate limiting and jitter
- Support IPv4 (224.0.1.187) and IPv6 (FF02::FD) CoAP addresses

**Integration Points:**
- `src/serve.rs:100-130`: Add multicast listener alongside DTLS listener
- `src/config.rs`: Add multicast configuration options
- Response handling with built-in rate limiting to prevent congestion

**Key Considerations:**
- Response congestion prevention (jitter, rate limiting)
- Duplicate response handling
- Integration with existing security model (multicast + DTLS challenges)

---

### 4. Link Format Parser (RFC 6690) - **HIGH FEASIBILITY**

**Priority:** Medium (Foundation for discovery)  
**Estimated Effort:** 1-2 weeks  
**Complexity:** Low

**Implementation Approach:**
- Create `LinkFormat` struct with parsing/serialization
- Support standard attributes (rel, rt, if, sz) and extensions
- Integrate with `.well-known/core` responses
- Add `LinkFormatResponse` type for handlers

**Integration Points:**
- New `src/link_format.rs` module
- `src/extract/`: `LinkFormat` extractor for parsing request payloads
- `src/response.rs`: `LinkFormatResponse` for generating discovery responses

**Syntax Support:**
- `<URI>; attribute1=value1; attribute2=value2` format
- Standard attributes: `rel`, `rt`, `if`, `sz`, `title`, `anchor`
- Multiple values and filtering capabilities

---

### 5. PATCH Method Support (RFC 8132) - **HIGH FEASIBILITY**

**Priority:** Low (Nice to have)  
**Estimated Effort:** 1 week  
**Complexity:** Low-Medium

**Implementation Approach:**
- Extend `coap-lite` RequestType enum (may need fork/upstream contribution)
- Add PATCH method to router builder: `.patch(path, handler)`
- Support JSON Patch (RFC 6902) and JSON Merge Patch (RFC 7396) content types
- Create `JsonPatch<T>` extractor for atomic updates

**Integration Points:**
- `src/router/mod.rs:200-250`: Add PATCH to method routing
- `src/extract/`: New `JsonPatch<T>` extractor
- Requires `coap-lite` enhancement or wrapper enum

**Content Format Support:**
- `application/json-patch+json` (Content-Format ID 51)
- `application/merge-patch+json` (Content-Format ID 52)

---

### 6. Event Streaming Interface - **HIGH FEASIBILITY**

**Priority:** Medium (Frontend integration)  
**Estimated Effort:** 1 week  
**Complexity:** Low

**Implementation Approach:**
- Create `ObserverStream` that converts observer events to async streams
- Add `stream_events()` method to router returning `Stream<ObserverValue>`
- Support filtering by device/path patterns
- Enable WebSocket bridge implementations

**Integration Points:**
- `src/observer/mod.rs:40-65`: Add stream conversion methods
- New `src/streaming.rs` with bridge utilities
- Leverages existing `tokio::sync::mpsc` infrastructure

**Benefits:**
- Easy WebSocket bridge for management frontends
- Real-time data streaming capabilities
- Filtered event subscriptions

## Implementation Priority Recommendation

1. **Link Format Parser** (1-2 weeks) - Foundation for discovery
2. **PATCH Method** (1 week) - Simple router extension  
3. **Multicast Support** (2-3 weeks) - Major capability addition
4. **Event Streaming** (1 week) - Enables frontend integration
5. **Block-wise Transfer** (3-4 weeks) - Complex but essential for firmware
6. **Resource Directory** (4-6 weeks) - Complete subsystem

**Total Estimated Effort:** 12-19 weeks for complete implementation

## Architecture Considerations

All features are designed to be:
- **Modular**: Each can be implemented independently
- **Backwards Compatible**: No breaking changes to existing API
- **Optional**: Feature flags where appropriate
- **Secure**: Follow existing security patterns and add new protections

The existing router and observer architecture provides an excellent foundation for these extensions without requiring major refactoring.

## Status

- **Last Updated:** 2025-01-18
- **Status:** Planning Phase
- **Next Steps:** Prioritize features and begin implementation

## Additional CoAP RFC Features for Consideration

Based on comprehensive RFC analysis, here are additional features that could enhance CoAPum:

### Security & Authentication

#### 7. OSCORE (RFC 8613) - **MEDIUM FEASIBILITY**
**Priority:** Medium (End-to-end security)  
**Estimated Effort:** 6-8 weeks  
**Complexity:** High

**What it provides:**
- End-to-end encryption and integrity protection for CoAP messages
- Works across intermediary nodes like proxies  
- Supports translation between different transport protocols
- Provides replay protection and message binding

**Implementation approach:**
- Add OSCORE context management for clients
- Implement CBOR Object Signing and Encryption (COSE) integration
- Create `OSCOREProtected<T>` extractor for secure message handling
- Support key derivation and context establishment

**Integration points:**
- `src/security/oscore.rs`: New module for OSCORE implementation
- `src/extract/`: Add OSCORE-aware extractors
- Requires additional dependencies: `cose-rust`, `cbor` libraries

#### 8. CoAP Security Extensions (RFC 9175) - **HIGH FEASIBILITY**
**Priority:** Medium (Attack mitigation)  
**Estimated Effort:** 2-3 weeks  
**Complexity:** Low-Medium

**Features:**
- **Echo Option**: Server-side request freshness verification
- **Request-Tag Option**: Protection for block-wise transfers
- **Enhanced Token Processing**: Better request-response binding

**Implementation approach:**
- Add Echo challenge/response handling to handlers
- Implement Request-Tag validation for block transfers
- Enhance token generation and validation

**Integration points:**
- `src/security/`: New security utilities module
- `src/extract/`: Add `Echo` and `RequestTag` extractors
- `src/serve.rs`: Enhanced token validation

### Transport & Protocol Extensions

#### 9. CoAP over TCP/TLS/WebSockets (RFC 8323) - **MEDIUM FEASIBILITY**
**Priority:** High (Frontend integration)  
**Estimated Effort:** 4-6 weeks  
**Complexity:** Medium-High

**Benefits:**
- Direct WebSocket support for web frontends
- Reliable transport for enterprise networks
- Larger message transfers via BERT (Block-Wise Transfer Extension)
- TLS security integration

**Implementation approach:**
- Add TCP/TLS/WebSocket listeners alongside UDP
- Implement Capabilities and Settings Message (CSM) handling
- Create transport-agnostic router interface
- Support bidirectional connections

**Integration points:**
- `src/transport/`: New transport abstraction layer
- `src/serve_tcp.rs`: TCP/TLS/WebSocket server implementation
- `src/config.rs`: Transport configuration options

#### 10. Extended Tokens (RFC 8974) - **HIGH FEASIBILITY**
**Priority:** Low (Optimization)  
**Estimated Effort:** 1-2 weeks  
**Complexity:** Low

**Benefits:**
- Support tokens up to 65,804 bytes
- Enable stateless client implementations
- Embed request state in tokens

**Implementation approach:**
- Extend token handling in CoAP message processing
- Add token serialization/deserialization utilities
- Support state embedding in tokens

### Group Communication & Multicast

#### 11. Advanced Group Communication (RFC 7390) - **MEDIUM FEASIBILITY**
**Priority:** Medium (Bulk operations)  
**Estimated Effort:** 3-5 weeks  
**Complexity:** Medium

**Features beyond basic multicast:**
- Group URI syntax support (`coap://[ff02::1]/sensors`)
- Response suppression patterns
- Reliable group communication patterns
- MPL (Multicast Protocol for Low-Power) forwarding

**Implementation approach:**
- Extend multicast support with group URI parsing
- Add response suppression based on No-Response option
- Implement reliable group communication helpers

#### 12. No-Response Option (RFC 7967) - **HIGH FEASIBILITY**
**Priority:** Low (Optimization)  
**Estimated Effort:** 1 week  
**Complexity:** Low

**Use cases:**
- High-frequency sensor updates
- Multicast actuation commands
- Battery optimization for constrained devices

**Implementation approach:**
- Add No-Response option parsing
- Implement selective response suppression
- Support response class bitmask (2.xx, 4.xx, 5.xx)

### Interoperability & Integration

#### 13. HTTP-CoAP Proxy (RFC 8075) - **HIGH FEASIBILITY**
**Priority:** High (Web integration)  
**Estimated Effort:** 4-6 weeks  
**Complexity:** Medium-High

**Benefits:**
- Enable HTTP clients to access CoAP resources
- Web browser compatibility
- RESTful API bridging for management frontends

**Implementation approach:**
- Create HTTP server that translates to CoAP requests
- Implement URI mapping and status code translation
- Support content-type and encoding translation
- Handle block-wise transfers transparently

**Integration points:**
- `src/proxy/`: New HTTP-CoAP proxy module
- Integration with existing router and handlers
- Support for both directions: HTTP→CoAP and CoAP→HTTP

#### 14. Certificate Management (RFC 9482) - **MEDIUM FEASIBILITY**
**Priority:** Low (Enterprise PKI)  
**Estimated Effort:** 6-8 weeks  
**Complexity:** High

**Features:**
- CoAP transport for Certificate Management Protocol (CMP)
- PKI certificate lifecycle management
- Integration with DTLS certificate-based authentication

**Implementation approach:**
- Add CMP message handling over CoAP
- Support certificate enrollment and renewal
- Implement PKI protection mechanisms

## Updated Implementation Priority

### Phase 1: Core Protocol Extensions (12-16 weeks)
1. **Link Format Parser** (1-2 weeks)
2. **PATCH Method** (1 week)  
3. **Block-wise Transfer** (3-4 weeks)
4. **Event Streaming** (1 week)
5. **CoAP Security Extensions** (2-3 weeks)
6. **No-Response Option** (1 week)
7. **Extended Tokens** (1-2 weeks)

### Phase 2: Transport & Integration (10-14 weeks)
8. **Multicast Support** (2-3 weeks)
9. **HTTP-CoAP Proxy** (4-6 weeks)
10. **CoAP over TCP/TLS/WebSockets** (4-6 weeks)

### Phase 3: Advanced Features (12-20 weeks)
11. **Resource Directory** (4-6 weeks)
12. **Advanced Group Communication** (3-5 weeks)
13. **OSCORE** (6-8 weeks)
14. **Certificate Management** (6-8 weeks)

**Total Estimated Effort:** 34-50 weeks for complete RFC compliance

### Data Format & Serialization Standards

#### 15. SenML Support (RFC 8428) - **HIGH FEASIBILITY**
**Priority:** High (Backend uniformity)  
**Estimated Effort:** 2-3 weeks  
**Complexity:** Low-Medium

**What it provides:**
- Standardized format for sensor measurements and device parameters
- Multiple serialization formats: JSON, CBOR, XML, EXI
- Native CoAP Content-Format IDs (110-115, 310-311)
- Efficient batch transmission of sensor data
- Time-series data support with base values and timestamps

**Implementation approach:**
- Create separate `coapum-senml` crate for core SenML functionality
- Implement SenML data structures (SenMLPack, SenMLRecord) with serde support
- Add validation and normalization according to RFC 8428
- Implement CoAPum extractor using the separate crate
- Support both JSON (110-111) and CBOR (112-113) Content-Formats
- Provide builder pattern for creating SenML packs
- Add time-series helpers for sensor data

**Architecture design:**
1. **`coapum-senml` crate** (reusable SenML logic):
   - Core data types with JSON/CBOR serialization
   - Validation and normalization functions
   - Builder patterns and time-series utilities
   - No CoAP dependencies

2. **CoAPum integration** (`src/extract/senml.rs`):
   - `SenML<T>` extractor with automatic format detection
   - `NormalizedSenML` for pre-normalized data
   - Response implementations for SenML types
   - Support for custom validated types

**Integration points:**
- New `coapum-senml` crate in workspace
- `src/extract/senml.rs`: SenML extractor implementation
- Automatic Content-Format handling (110-115)
- Integration with existing extractor patterns

**Example implementation:**
```rust
// Handler using SenML extractor
async fn update_sensors(
    Path(device_id): Path<String>,
    SenML(pack): SenML<SenMLPack>,
) -> Result<StatusCode, SenMLRejection> {
    // Process normalized sensor data
    let normalized = pack.normalize();
    for record in normalized.records {
        // Handle each measurement
    }
    Ok(StatusCode::Changed)
}

// Type-safe sensor data
#[derive(Deserialize, Validate)]
struct TemperatureReading {
    #[validate(range(min = -50.0, max = 100.0))]
    temperature: f64,
    unit: String,
}

async fn update_temperature(
    SenML(temp): SenML<TemperatureReading>,
) -> StatusCode {
    StatusCode::Changed
}
```

**Benefits of separate crate approach:**
- Reusable SenML implementation for Rust ecosystem
- Clean separation of concerns
- Type-safe sensor data handling
- Automatic format negotiation
- Built-in RFC 8428 validation

#### 16. Multipart Content-Format (RFC 8710) - **HIGH FEASIBILITY**
**Priority:** Medium (Bulk operations)  
**Estimated Effort:** 1-2 weeks  
**Complexity:** Low

**Features:**
- Combine multiple representations in single CoAP message
- Minimal framing overhead using CBOR arrays
- Support for mixed content types in one request
- Efficient batch operations for management systems

**Implementation approach:**
- Parse multipart CBOR arrays in request handling
- Support mixed content-format processing
- Create `Multipart` extractor for batch operations
- Enable bulk sensor data updates

#### 17. SenML FETCH/PATCH Extensions (RFC 8790) - **MEDIUM FEASIBILITY**
**Priority:** Medium (Efficient updates)  
**Estimated Effort:** 2-3 weeks  
**Complexity:** Medium

**Features:**
- Batch sensor data collection with FETCH
- Partial resource updates using PATCH
- Resource collections in single requests
- Query-based data retrieval

**Implementation approach:**
- Extend PATCH support with SenML payloads
- Implement FETCH method for bulk queries
- Support SenML-based partial updates
- Add query parameter processing for collections

### Recommended Minimal Viable Product (MVP)
For management frontend support, prioritize:
1. **Block-wise Transfer** - Essential for firmware updates
2. **HTTP-CoAP Proxy** - Critical for web frontend integration  
3. **Event Streaming** - Real-time data for dashboards
4. **SenML Support** - Standardized sensor data format
5. **CoAP Security Extensions** - Basic attack mitigation

**MVP Effort:** 12-18 weeks

### Complete Backend Uniformity Stack
For full sensor data standardization:
1. **SenML (RFC 8428)** - Core data format
2. **Multipart Content-Format (RFC 8710)** - Batch operations
3. **SenML FETCH/PATCH (RFC 8790)** - Efficient updates
4. **CBOR enhancements** - Already partially implemented

**Backend Uniformity Effort:** 5-8 weeks

---

*This document will be updated as implementation progresses and requirements evolve.*