forge
Explore
Log in

Don't you dare go Hollow

Apps fetch photos with client credentials

Browse files at this commit

569b89d4a8ebe700af13c337ddbd051a35572d89Ahmet Kaan GümüşParent: 4e48172
  • feat
    • apps fetch photos with client credentials
Show full message
feat(oidc): apps fetch photos with client credentials

GET /photo/{user_id} answered only to a signed-in session, so a relying
party's pages could never show a person's photo: an <img> from another
origin carries no SameSite=Lax cookie. Registered apps now authenticate
with Authorization: Basic base64(client_id:client_secret), checked
against the client registry. Sessions still win when both arrive, and
every failure — bad credentials, unknown client, unknown person,
missing photo — is the same 404.
crates/im-web/src/photo.rsmodified+270 -3
@@ -167,11 +167,19 @@ fn not_found() -> (StatusCode, HeaderMap, Vec<u8>) {
167 (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new())167 (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new())
168 }168 }
169 169
170-/// Serves one person's photo. Signed-in only, and a missing photo reads170+/// Serves one person's photo. Signed-in only — either through the session
171-/// exactly like a missing person: the not-found, never a `403`.171+/// cookie or as a registered OIDC app presenting HTTP Basic over
172+/// `client_id:client_secret` — and a missing photo reads exactly like a
173+/// missing person: the not-found, never a `403`.
174+///
175+/// Apps count as signed-in viewers because registration is the trust: im
176+/// hands the client secret out exactly once, keeps only its digest, and the
177+/// app presents it on every fetch. Unknown clients, wrong secrets, unknown
178+/// users and missing photos all answer the same not-found, so no failure
179+/// is distinguishable on the wire.
172 #[route(GET "/photo/{user_id}")]180 #[route(GET "/photo/{user_id}")]
173 async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {181 async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
174- if server::current_user(cx).await.is_none() {182+ if server::current_user(cx).await.is_none() && !valid_app(cx).await {
175 return Ok(not_found());183 return Ok(not_found());
176 }184 }
177 let target = im_core::model::UserId::from(path_param::<UserId>(cx).to_string());185 let target = im_core::model::UserId::from(path_param::<UserId>(cx).to_string());
@@ -206,3 +214,262 @@ async fn serve(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
206 );214 );
207 Ok((StatusCode::OK, headers, bytes))215 Ok((StatusCode::OK, headers, bytes))
208 }216 }
217+
218+/// Whether this request carries a registered OIDC app's credentials: HTTP
219+/// Basic over `client_id:client_secret`, checked against the client
220+/// registry. Anything unparseable, unknown, or wrong is simply false — the
221+/// caller answers its one not-found and never says which.
222+async fn valid_app(cx: &Cx) -> bool {
223+ use base64::Engine as _;
224+ let Some(encoded) = request_headers(cx)
225+ .get(header::AUTHORIZATION)
226+ .and_then(|value| value.to_str().ok())
227+ .and_then(|value| value.strip_prefix("Basic "))
228+ else {
229+ return false;
230+ };
231+ let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(encoded) else {
232+ return false;
233+ };
234+ let Ok(pair) = std::str::from_utf8(&decoded) else {
235+ return false;
236+ };
237+ let Some((client_id, secret)) = pair.split_once(':') else {
238+ return false;
239+ };
240+ let store = server::app(cx).store.clone();
241+ let Ok(Some(client)) = im_core::oidc::client_by_id(&store, client_id).await else {
242+ return false;
243+ };
244+ im_core::oidc::verify_client_secret(&client, secret)
245+}
246+
247+#[cfg(test)]
248+mod tests {
249+ use std::path::Path;
250+ use std::sync::Arc;
251+
252+ use im_core::accounts::{create_invite, create_user_from_invite};
253+ use im_core::model::UserId;
254+ use im_core::oidc::create_client;
255+ use im_core::photos::set_photo;
256+ use im_core::sessions::{SessionMeta, create_session};
257+ use im_core::store::Store;
258+ use topcoat::cookie::RouterBuilderCookieExt as _;
259+ use topcoat::router::{Body, HeaderMap, Router, RouterBuilderDiscoverExt as _, StatusCode};
260+ use topcoat::router::{header, to_bytes};
261+ use super::PhotoStamps;
262+
263+ use crate::config::Config;
264+ use crate::server::{self, SESSION_COOKIE};
265+
266+ const PHOTO: &[u8] = b"\x89PNG\r\n\x1a\nfake-photo-bytes";
267+
268+ struct Setup {
269+ router: Router,
270+ user_id: UserId,
271+ plain_id: UserId,
272+ client_id: String,
273+ secret: String,
274+ session_cookie: String,
275+ }
276+
277+ async fn setup() -> Setup {
278+ let store = Store::open(Path::new(":memory:")).await.unwrap();
279+ let (client_id, secret) = create_client(&store, "drive", vec!["http://app/callback".into()])
280+ .await
281+ .unwrap();
282+ let invite = create_invite(&store, "ann@example.com", None, false)
283+ .await
284+ .unwrap();
285+ let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
286+ .await
287+ .unwrap();
288+ set_photo(&store, &user.id, PHOTO, "image/png")
289+ .await
290+ .unwrap();
291+ let bare = create_invite(&store, "ben@example.com", None, false)
292+ .await
293+ .unwrap();
294+ let plain = create_user_from_invite(&store, bare.expose(), "Ben", "tDLr9!mZQ2xv")
295+ .await
296+ .unwrap();
297+ let session = create_session(&store, &user.id, &SessionMeta::default())
298+ .await
299+ .unwrap();
300+ let (live, _) = tokio::sync::broadcast::channel(64);
301+ let app = server::App {
302+ store: Arc::new(store),
303+ config: Config {
304+ database: ":memory:".into(),
305+ listen: "127.0.0.1:7650".parse().unwrap(),
306+ issuer: "http://127.0.0.1:7650".into(),
307+ },
308+ live,
309+ };
310+ let router = Router::builder()
311+ .discover()
312+ .cookies()
313+ .app_context(app)
314+ .app_context(PhotoStamps::default())
315+ .build();
316+ Setup {
317+ router,
318+ user_id: user.id,
319+ plain_id: plain.id,
320+ client_id: client_id.to_string(),
321+ secret: secret.expose().to_string(),
322+ session_cookie: format!("{SESSION_COOKIE}={}", session.expose()),
323+ }
324+ }
325+
326+ fn basic(client_id: &str, secret: &str) -> String {
327+ use base64::Engine as _;
328+ format!(
329+ "Basic {}",
330+ base64::engine::general_purpose::STANDARD.encode(format!("{client_id}:{secret}"))
331+ )
332+ }
333+
334+ async fn get(
335+ router: &Router,
336+ user_id: &str,
337+ auth: Option<String>,
338+ cookie: Option<&str>,
339+ ) -> (StatusCode, HeaderMap, Vec<u8>) {
340+ let mut builder = http::Request::builder().uri(format!("/photo/{user_id}"));
341+ if let Some(auth) = auth {
342+ builder = builder.header(header::AUTHORIZATION, auth);
343+ }
344+ if let Some(cookie) = cookie {
345+ builder = builder.header(header::COOKIE, cookie);
346+ }
347+ let response = router.handle(builder.body(Body::empty()).unwrap()).await;
348+ let (parts, body) = response.into_parts();
349+ let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec();
350+ (parts.status, parts.headers, bytes)
351+ }
352+
353+ #[tokio::test]
354+ async fn app_credentials_serve_photo_bytes() {
355+ let setup = setup().await;
356+ let (status, headers, bytes) = get(
357+ &setup.router,
358+ setup.user_id.as_str(),
359+ Some(basic(&setup.client_id, &setup.secret)),
360+ None,
361+ )
362+ .await;
363+ assert_eq!(status, StatusCode::OK);
364+ assert_eq!(bytes, PHOTO);
365+ assert_eq!(
366+ headers.get(header::CONTENT_TYPE).unwrap(),
367+ "image/png"
368+ );
369+ }
370+
371+ #[tokio::test]
372+ async fn wrong_secret_is_not_found() {
373+ let setup = setup().await;
374+ let (status, _, bytes) = get(
375+ &setup.router,
376+ setup.user_id.as_str(),
377+ Some(basic(&setup.client_id, "wrong-secret")),
378+ None,
379+ )
380+ .await;
381+ assert_eq!(status, StatusCode::NOT_FOUND);
382+ assert!(bytes.is_empty());
383+ }
384+
385+ #[tokio::test]
386+ async fn unknown_client_is_not_found() {
387+ let setup = setup().await;
388+ let (status, _, bytes) = get(
389+ &setup.router,
390+ setup.user_id.as_str(),
391+ Some(basic("no-such-client", &setup.secret)),
392+ None,
393+ )
394+ .await;
395+ assert_eq!(status, StatusCode::NOT_FOUND);
396+ assert!(bytes.is_empty());
397+ }
398+
399+ #[tokio::test]
400+ async fn no_credentials_is_not_found() {
401+ let setup = setup().await;
402+ let (status, _, bytes) = get(&setup.router, setup.user_id.as_str(), None, None).await;
403+ assert_eq!(status, StatusCode::NOT_FOUND);
404+ assert!(bytes.is_empty());
405+ }
406+
407+ #[tokio::test]
408+ async fn malformed_authorization_is_not_found() {
409+ let setup = setup().await;
410+ let (status, _, _) = get(
411+ &setup.router,
412+ setup.user_id.as_str(),
413+ Some("Basic !!!not-base64!!!".to_string()),
414+ None,
415+ )
416+ .await;
417+ assert_eq!(status, StatusCode::NOT_FOUND);
418+ }
419+
420+ #[tokio::test]
421+ async fn app_credentials_unknown_user_is_not_found() {
422+ let setup = setup().await;
423+ let (status, _, bytes) = get(
424+ &setup.router,
425+ "no-such-user",
426+ Some(basic(&setup.client_id, &setup.secret)),
427+ None,
428+ )
429+ .await;
430+ assert_eq!(status, StatusCode::NOT_FOUND);
431+ assert!(bytes.is_empty());
432+ }
433+
434+ #[tokio::test]
435+ async fn app_credentials_missing_photo_is_not_found() {
436+ let setup = setup().await;
437+ let (status, _, bytes) = get(
438+ &setup.router,
439+ setup.plain_id.as_str(),
440+ Some(basic(&setup.client_id, &setup.secret)),
441+ None,
442+ )
443+ .await;
444+ assert_eq!(status, StatusCode::NOT_FOUND);
445+ assert!(bytes.is_empty());
446+ }
447+
448+ #[tokio::test]
449+ async fn session_still_serves_photo() {
450+ let setup = setup().await;
451+ let (status, _, bytes) = get(
452+ &setup.router,
453+ setup.user_id.as_str(),
454+ None,
455+ Some(&setup.session_cookie),
456+ )
457+ .await;
458+ assert_eq!(status, StatusCode::OK);
459+ assert_eq!(bytes, PHOTO);
460+ }
461+
462+ #[tokio::test]
463+ async fn session_takes_precedence_over_bad_app_credentials() {
464+ let setup = setup().await;
465+ let (status, _, bytes) = get(
466+ &setup.router,
467+ setup.user_id.as_str(),
468+ Some(basic(&setup.client_id, "wrong-secret")),
469+ Some(&setup.session_cookie),
470+ )
471+ .await;
472+ assert_eq!(status, StatusCode::OK);
473+ assert_eq!(bytes, PHOTO);
474+ }
475+}