Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

### Added

- r9cam cameras can sign their device tokens with EdDSA (Ed25519) as well as ES256. Each camera
may use only the algorithm of the key it paired with. The backend now uses r9cam-models
0.7.0, which accepts Ed25519 public keys at pairing. ([#501](https://github.com/CMLPlatform/r9lab/issues/501))
- An accessibility statement at `/accessibility` on the website, backed by a WCAG 2.2
self-assessment of the website, the documentation site and the web app at
`/accessibility-assessment`.
Expand Down
37 changes: 29 additions & 8 deletions app/src/types/api.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2551,7 +2551,7 @@ export interface paths {
post?: never;
/**
* Pi-initiated self-unpair
* @description Called by the Pi when the user triggers unpair from the local /setup page. Authenticates via the device's ES256 assertion. Deletes the camera from the database so the backend no longer shows it as offline.
* @description Called by the Pi when the user triggers unpair from the local /setup page. Authenticates via the device's assertion. Deletes the camera from the database so the backend no longer shows it as offline.
*/
delete: operations['self_unpair_camera_v1_plugins_r9cam_device_cameras__camera_id__self_delete'];
options?: never;
Expand All @@ -2570,7 +2570,7 @@ export interface paths {
put?: never;
/**
* Internal: receive an image pushed directly from a paired Raspberry Pi
* @description Called by the Pi after a successful capture. Authenticated with a short-lived ES256 device assertion (same credential used by the WebSocket relay). The Pi provides the JPEG body plus two JSON blobs: `capture_metadata` (libcamera metadata) and `upload_metadata` (opaque dict forwarded by whichever caller triggered the capture, typically `{product_id, description}`). The backend stores the image via the normal image storage service and returns a tiny ack envelope the Pi consumes.
* @description Called by the Pi after a successful capture. Authenticated with a short-lived device assertion (same credential used by the WebSocket relay). The Pi provides the JPEG body plus two JSON blobs: `capture_metadata` (libcamera metadata) and `upload_metadata` (opaque dict forwarded by whichever caller triggered the capture, typically `{product_id, description}`). The backend stores the image via the normal image storage service and returns a tiny ack envelope the Pi consumes.
*/
post: operations['receive_camera_upload_v1_plugins_r9cam_device_cameras__camera_id__image_upload_post'];
delete?: never;
Expand All @@ -2590,7 +2590,7 @@ export interface paths {
put?: never;
/**
* Internal: receive a cached preview thumbnail pushed directly from a paired Raspberry Pi
* @description Called by the Pi's background thumbnail worker. Authenticated with the same short-lived ES256 device assertion used by the WebSocket relay. Stores a deterministic per-camera JPEG cache file for camera-card previews without creating an Image database row.
* @description Called by the Pi's background thumbnail worker. Authenticated with the same short-lived device assertion used by the WebSocket relay. Stores a deterministic per-camera JPEG cache file for camera-card previews without creating an Image database row.
*/
post: operations['receive_preview_thumbnail_upload_v1_plugins_r9cam_device_cameras__camera_id__preview_thumbnail_upload_post'];
delete?: never;
Expand Down Expand Up @@ -3253,6 +3253,21 @@ export interface components {
* @description Sensor temperature in °C
*/
sensor_temperature?: number | null;
/**
* Lens Position
* @description Lens focus position in dioptres
*/
lens_position?: number | null;
/**
* Color Gains
* @description Red and blue white-balance gains
*/
color_gains?: [number, number] | null;
/**
* Scaler Crop
* @description Sensor area read for the image as x, y, width, height in sensor pixels
*/
scaler_crop?: [number, number, number, number] | null;
};
/**
* CategoriesResponse
Expand Down Expand Up @@ -3935,7 +3950,9 @@ export interface components {
};
/**
* DevicePublicKeyJWK
* @description Public P-256 JWK registered by the Pi during pairing.
* @description Public JWK registered by the Pi during pairing: EC P-256 (ES256) or OKP Ed25519 (EdDSA).
*
* ``alg`` is optional, as in RFC 7517: ``kty`` and ``crv`` already fix the algorithm.
*/
DevicePublicKeyJWK: {
/** Kty */
Expand All @@ -3945,7 +3962,9 @@ export interface components {
/** X */
x: string;
/** Y */
y: string;
y?: string | null;
/** Alg */
alg?: ('ES256' | 'EdDSA') | null;
/** Use */
use?: string | null;
/** Kid */
Expand Down Expand Up @@ -4799,7 +4818,7 @@ export interface components {
* @description Random nonce generated by the Pi. Required to retrieve credentials later.
*/
rpi_fingerprint: string;
/** @description Public P-256 JWK generated by the Pi. */
/** @description Public JWK (P-256 or Ed25519) generated by the Pi. */
public_key_jwk: components['schemas']['DevicePublicKeyJWK'];
/** Key Id */
key_id: string;
Expand Down Expand Up @@ -5344,7 +5363,7 @@ export interface components {
RelayAuthScheme: 'device_assertion';
/**
* RelayPublicKeyJWK
* @description Public P-256 JWK registered by an RPi camera.
* @description Public JWK registered by an RPi camera: P-256 for ES256 or Ed25519 for EdDSA.
*/
RelayPublicKeyJWK: {
/** Kty */
Expand All @@ -5354,7 +5373,9 @@ export interface components {
/** X */
x: string;
/** Y */
y: string;
y?: string | null;
/** Alg */
alg?: ('ES256' | 'EdDSA') | null;
/** Use */
use?: string | null;
/** Kid */
Expand Down
2 changes: 1 addition & 1 deletion app/src/types/openapi.json

Large diffs are not rendered by default.

12 changes: 8 additions & 4 deletions backend/app/api/plugins/r9cam/device_assertion.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Shared device-assertion verification used by the WebSocket relay and HTTP endpoints.

Both transports accept the same ES256 JWT minted by the Pi (``build_device_assertion``
Both transports accept the same ES256 or EdDSA JWT minted by the Pi (``build_device_assertion``
in ``r9cam/app/relay/device_jwt.py``): the audience is shared, the
replay-protection namespace in Redis is shared, and the verification logic is
therefore identical. Keeping it in one place prevents drift between the two
Expand Down Expand Up @@ -34,7 +34,10 @@
# backend and the Pis can be upgraded in either order.
# TODO(drop-by 2027-01-31): drop together with the /v1/plugins/rpi-cam/ prefix
LEGACY_ASSERTION_AUDIENCE = "relab-rpi-cam-relay"
ASSERTION_ALGORITHMS = ("ES256",)
ASSERTION_ALGORITHMS = ("ES256", "EdDSA")
# The key type registered at pairing fixes the one algorithm a camera may sign with, so a
# token cannot pick a different algorithm than its key was made for.
_ALGORITHM_BY_KEY_TYPE = {"EC": "ES256", "OKP": "EdDSA"}
REPLAY_KEY_PREFIX = "r9cam:relay_assertion_jti:"
MAX_ASSERTION_TTL_SECONDS = 5 * 60

Expand All @@ -60,7 +63,8 @@ async def verify_device_assertion(assertion: str, camera: Camera, redis: Redis)
enforced via a one-shot Redis ``SET NX`` keyed by ``{camera.id}:{jti}``.
"""
header = jwt.get_unverified_header(assertion)
if header.get("alg") not in ASSERTION_ALGORITHMS:
algorithm = _ALGORITHM_BY_KEY_TYPE.get(camera.relay_public_key_jwk.get("kty"))
if algorithm is None or header.get("alg") != algorithm:
msg = "Unsupported assertion algorithm"
raise InvalidTokenError(msg)
if header.get("kid") != camera.relay_key_id:
Expand All @@ -71,7 +75,7 @@ async def verify_device_assertion(assertion: str, camera: Camera, redis: Redis)
payload = jwt.decode(
assertion,
key=public_key,
algorithms=list(ASSERTION_ALGORITHMS),
algorithms=[algorithm],
audience=[ASSERTION_AUDIENCE, LEGACY_ASSERTION_AUDIENCE],
options={"require": ["exp", "iat", "iss", "nbf", "jti", "sub"]},
)
Expand Down
2 changes: 1 addition & 1 deletion backend/app/api/plugins/r9cam/routers/camera_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ async def delete_user_camera(
status_code=204,
description=(
"Called by the Pi when the user triggers unpair from the local /setup page. "
"Authenticates via the device's ES256 assertion. Deletes the camera from the "
"Authenticates via the device's assertion. Deletes the camera from the "
"database so the backend no longer shows it as offline."
),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ async def capture_image(
response_model=DeviceImageUploadAck,
summary="Internal: receive an image pushed directly from a paired Raspberry Pi",
description=(
"Called by the Pi after a successful capture. Authenticated with a short-lived ES256 "
"Called by the Pi after a successful capture. Authenticated with a short-lived "
"device assertion (same credential used by the WebSocket relay). The Pi provides the "
"JPEG body plus two JSON blobs: `capture_metadata` (libcamera metadata) and "
"`upload_metadata` (opaque dict forwarded by whichever caller triggered the capture, "
Expand Down Expand Up @@ -211,7 +211,7 @@ async def receive_camera_upload(
summary="Internal: receive a cached preview thumbnail pushed directly from a paired Raspberry Pi",
description=(
"Called by the Pi's background thumbnail worker. Authenticated with the same short-lived "
"ES256 device assertion used by the WebSocket relay. Stores a deterministic per-camera JPEG "
"device assertion used by the WebSocket relay. Stores a deterministic per-camera JPEG "
"cache file for camera-card previews without creating an Image database row."
),
status_code=201,
Expand Down
2 changes: 1 addition & 1 deletion backend/app/api/plugins/r9cam/schemas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class CameraFilterWithOwner(CameraFilter):


class RelayPublicKeyJWK(DevicePublicKeyJWK):
"""Public P-256 JWK registered by an RPi camera."""
"""Public JWK registered by an RPi camera: P-256 for ES256 or Ed25519 for EdDSA."""


class CameraCreate(BaseCreateSchema, CameraBase):
Expand Down
2 changes: 1 addition & 1 deletion backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"sqlalchemy>=2.0.41",
# Shared application models and outbound integrations
"httpx[http2]>=0.28.1",
"r9cam-models>=0.6.0,<0.7",
"r9cam-models>=0.7.0,<0.8",
# Configuration, validation, and utility types
# 2.14.0 and 2.14.1 cannot pickle parametrized generics such as the cached Page
# responses (pydantic#13991); drop the exclusion once 2.14.2 ships the fix.
Expand Down
21 changes: 17 additions & 4 deletions backend/tests/fixtures/device_assertion.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,23 @@
from typing import TYPE_CHECKING

import jwt
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec, ed25519

from app.api.plugins.r9cam.device_assertion import ASSERTION_AUDIENCE

if TYPE_CHECKING:
from uuid import UUID


def make_eddsa_keypair() -> tuple[ed25519.Ed25519PrivateKey, dict]:
"""Generate an Ed25519 key pair and return (private_key, public_jwk), as r9cam's EdDSA pairing sends it."""
private_key = ed25519.Ed25519PrivateKey.generate()
raw = private_key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
x = base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
return private_key, {"kty": "OKP", "crv": "Ed25519", "x": x, "alg": "EdDSA"}


def make_keypair() -> tuple[ec.EllipticCurvePrivateKey, dict]:
"""Generate an EC P-256 key pair and return (private_key, public_jwk)."""
private_key = ec.generate_private_key(ec.SECP256R1())
Expand All @@ -26,7 +35,7 @@ def _b64(n: int) -> str:


def sign_assertion(
private_key: ec.EllipticCurvePrivateKey,
private_key: ec.EllipticCurvePrivateKey | ed25519.Ed25519PrivateKey,
camera_id: UUID | str,
key_id: str,
*,
Expand All @@ -38,7 +47,10 @@ def sign_assertion(
omit_claims: set[str] | None = None,
headers: dict[str, object] | None = None,
) -> str:
"""Sign a device assertion for ``camera_id``; ``jti=""`` is kept as given."""
"""Sign a device assertion for ``camera_id``; ``jti=""`` is kept as given.

The algorithm follows the key type: ES256 for P-256, EdDSA for Ed25519.
"""
now = int(time.time())
payload = {
"iss": iss or f"camera:{camera_id}",
Expand All @@ -51,4 +63,5 @@ def sign_assertion(
}
for claim in omit_claims or set():
payload.pop(claim, None)
return jwt.encode(payload, private_key, algorithm="ES256", headers=headers or {"kid": key_id})
algorithm = "EdDSA" if isinstance(private_key, ed25519.Ed25519PrivateKey) else "ES256"
return jwt.encode(payload, private_key, algorithm=algorithm, headers=headers or {"kid": key_id})
2 changes: 1 addition & 1 deletion backend/tests/integration/db/test_r9cam_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async def test_create_camera(db_session: AsyncSession, db_superuser: User) -> No
camera_in = CameraCreate(
name=TEST_CAMERA_NAME,
description=TEST_CAMERA_DESC,
relay_public_key_jwk=RelayPublicKeyJWK(**PUBLIC_JWK),
relay_public_key_jwk=RelayPublicKeyJWK.model_validate(PUBLIC_JWK),
relay_key_id=KEY_ID,
)

Expand Down
50 changes: 49 additions & 1 deletion backend/tests/unit/plugins/r9cam/test_device_assertion.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from app.api.common.routers.exceptions import _response_parts
from app.api.plugins.r9cam import device_assertion as da
from app.core.runtime import RequiredServiceUnavailableError
from tests.fixtures.device_assertion import make_keypair, sign_assertion
from tests.fixtures.device_assertion import make_eddsa_keypair, make_keypair, sign_assertion

if TYPE_CHECKING:
from cryptography.hazmat.primitives.asymmetric import ec
Expand Down Expand Up @@ -249,3 +249,51 @@ async def test_inactive_owner_camera_is_rejected(*, is_active: bool, is_verified
):
await da._authenticated_camera(request, camera.id, session)
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED


# ── verify_device_assertion: algorithm per key type ──────────────────────────


def _camera_with_jwk(jwk: dict) -> MagicMock:
camera = MagicMock()
camera.id = uuid4()
camera.relay_key_id = "kid-1"
camera.relay_public_key_jwk = jwk
return camera


async def test_eddsa_assertion_from_an_ed25519_camera_is_accepted() -> None:
"""A camera paired with an Ed25519 key authenticates with EdDSA tokens."""
private_key, jwk = make_eddsa_keypair()
camera = _camera_with_jwk(jwk)
redis = AsyncMock()
redis.set.return_value = True

payload = await da.verify_device_assertion(sign_assertion(private_key, camera.id, "kid-1"), camera, redis)

assert payload["sub"] == f"camera:{camera.id}"


async def test_token_algorithm_must_match_the_registered_key_type() -> None:
"""An Ed25519 camera's key cannot be used for an ES256 token, and the reverse."""
eddsa_key, eddsa_jwk = make_eddsa_keypair()
ec_key, ec_jwk = make_keypair()
redis = AsyncMock()
redis.set.return_value = True

for key, jwk in ((ec_key, eddsa_jwk), (eddsa_key, ec_jwk)):
camera = _camera_with_jwk(jwk)
token = sign_assertion(key, camera.id, "kid-1")
with pytest.raises(jwt.InvalidTokenError, match="Unsupported assertion algorithm"):
await da.verify_device_assertion(token, camera, redis)


async def test_unknown_key_type_is_rejected() -> None:
"""A stored JWK of a key type with no allowed algorithm never authenticates."""
private_key, jwk = make_keypair()
camera = _camera_with_jwk({**jwk, "kty": "RSA"})
redis = AsyncMock()
redis.set.return_value = True

with pytest.raises(jwt.InvalidTokenError, match="Unsupported assertion algorithm"):
await da.verify_device_assertion(sign_assertion(private_key, camera.id, "kid-1"), camera, redis)
22 changes: 22 additions & 0 deletions backend/tests/unit/plugins/r9cam/test_pairing_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@
"y": "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
"kid": "key-12345",
}
ED25519_JWK = {
"kty": "OKP",
"crv": "Ed25519",
"x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo",
"alg": "EdDSA",
"kid": "key-12345",
}
KEY_ID = "key-12345"
PAIRING_CODE = "ABCD23"
PAIRING_LOG_ID = rate_limit_bucket_key("r9cam:pairing", PAIRING_CODE)
Expand Down Expand Up @@ -385,3 +392,18 @@ async def test_poll_pairing_status_reads_body_and_logs_digest(redis_client: Redi
mock_logger.info.assert_called_once_with("Pairing credentials retrieved for code %s.", PAIRING_LOG_ID)
assert PAIRING_CODE not in mock_logger.info.call_args.args[1]
assert await redis_client.get(f"r9cam:pairing:{PAIRING_CODE}") is None


async def test_register_pairing_code_accepts_an_ed25519_key(redis_client: Redis) -> None:
"""A Pi that pairs with an Ed25519 key (r9cam 0.8 default) registers like a P-256 one."""
body = PairingRegisterRequest(
code=PAIRING_CODE,
rpi_fingerprint="fingerprint",
public_key_jwk=ED25519_JWK,
key_id=KEY_ID,
)

await register_pairing_code(body=body, redis=redis_client)

stored = json.loads(await redis_client.get(f"r9cam:pairing:{PAIRING_CODE}"))
assert stored["public_key_jwk"] == ED25519_JWK
8 changes: 4 additions & 4 deletions backend/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading