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
12 changes: 10 additions & 2 deletions crates/exact-api/src/compat/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,16 @@ mod tests {
assert!(validate(GLOBAL, 0, &mut json!({"frame": 3})));
assert!(validate(GLOBAL, 0, &mut json!({"frame": "3"})));
// the dummy box that EXACT's own check asks for is still accepted, with or without a frame
assert!(validate(GLOBAL, 0, &mut json!({"x1": 0, "y1": 0, "x2": 1, "y2": 1})));
assert!(validate(GLOBAL, 0, &mut json!({"x1": 0, "y1": 0, "x2": 1, "y2": 1, "frame": 2})));
assert!(validate(
GLOBAL,
0,
&mut json!({"x1": 0, "y1": 0, "x2": 1, "y2": 1})
));
assert!(validate(
GLOBAL,
0,
&mut json!({"x1": 0, "y1": 0, "x2": 1, "y2": 1, "frame": 2})
));
// anything in between is not a vector of either kind
assert!(!validate(GLOBAL, 0, &mut json!({"x1": 1, "y1": 2})));
assert!(!validate(GLOBAL, 0, &mut json!({"frame": 2, "z": 1})));
Expand Down
7 changes: 5 additions & 2 deletions crates/exact-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ pub mod health;
pub mod media;
pub mod page;
pub mod repair;
pub mod slides;
pub mod scope;
pub mod slides;
pub mod upload;
pub mod v2;

Expand Down Expand Up @@ -97,7 +97,10 @@ pub fn router(state: AppState) -> Router {
// request bodies with files (bitmaps, media files) are larger than axum's default 2 MB
.layer(axum::extract::DefaultBodyLimit::max(1 << 30))
// limited personal access tokens: refused before anything runs when they go beyond their scopes
.layer(axum::middleware::from_fn_with_state(state.clone(), scope::enforce))
.layer(axum::middleware::from_fn_with_state(
state.clone(),
scope::enforce,
))
.with_state(state);
// uploaded files (file fields); public like Django's `/media/`
let r = r.nest_service("/media", tower_http::services::ServeDir::new(media_root));
Expand Down
69 changes: 55 additions & 14 deletions crates/exact-api/src/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ pub fn needed(method: &Method, path: &str) -> Option<&'static str> {
| ["images", "api", ..]
| ["images", "image", ..] => "images",
// products and annotation types
["api", "v2", "products", ..] | ["api", "v2", "annotation-types", ..] | ["administration", "api", "annotation_type", ..] => "catalog",
["api", "v2", "products", ..]
| ["api", "v2", "annotation-types", ..]
| ["administration", "api", "annotation_type", ..] => "catalog",
_ => return None,
})
}
Expand All @@ -75,7 +77,8 @@ pub async fn enforce(State(s): State<AppState>, req: Request, next: Next) -> Res
.and_then(|v| v.to_str().ok())
.and_then(|v| {
let (kind, t) = v.split_once(' ')?;
kind.eq_ignore_ascii_case("bearer").then(|| t.trim().to_string())
kind.eq_ignore_ascii_case("bearer")
.then(|| t.trim().to_string())
});
let Some(prefix) = token.as_deref().and_then(tokens::pat_prefix) else {
return next.run(req).await;
Expand Down Expand Up @@ -106,7 +109,11 @@ mod tests {
use super::*;

fn ok(scopes: &[&str], m: Method, p: &str) -> bool {
allows(&scopes.iter().map(|s| s.to_string()).collect::<Vec<_>>(), &m, p)
allows(
&scopes.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
&m,
p,
)
}

#[test]
Expand All @@ -124,13 +131,26 @@ mod tests {
assert!(ok(&j, Method::POST, "/api/v2/jobs/plugin/9/restart"));
assert!(ok(&j, Method::DELETE, "/api/v2/jobs/plugin/9"));
assert!(ok(&j, Method::POST, "/api/v2/registrations/manual"));
assert!(ok(&j, Method::POST, "/api/v1/images/images/5/register_images/"));
assert!(ok(
&j,
Method::POST,
"/api/v1/images/images/5/register_images/"
));
assert!(!ok(&j, Method::POST, "/api/v2/annotations"));
assert!(!ok(&j, Method::PATCH, "/api/v2/images/5"));
assert!(!ok(&j, Method::POST, "/api/v2/image-sets/3/images"));
// worker routes, accounts, tokens and configuration are for nobody who is limited
for p in ["/api/v2/jobs/claim", "/api/v2/plugin-jobs/3/complete", "/api/v2/registration-jobs/3/fail", "/api/v2/plugins/register",
"/api/v2/users/3", "/api/v2/teams/1/members/4", "/api/v2/me/tokens", "/api/v2/me/preferences", "/api/v2/admin/users"] {
for p in [
"/api/v2/jobs/claim",
"/api/v2/plugin-jobs/3/complete",
"/api/v2/registration-jobs/3/fail",
"/api/v2/plugins/register",
"/api/v2/users/3",
"/api/v2/teams/1/members/4",
"/api/v2/me/tokens",
"/api/v2/me/preferences",
"/api/v2/admin/users",
] {
assert!(!ok(&SCOPES, Method::POST, p), "{p}");
assert!(!ok(&SCOPES, Method::DELETE, p), "{p}");
}
Expand All @@ -139,12 +159,21 @@ mod tests {
#[test]
fn catalog_covers_products_and_annotation_types_and_nothing_else() {
let c = ["catalog"];
for (m, p) in [(Method::POST, "/api/v2/products"), (Method::PATCH, "/api/v2/products/4"), (Method::DELETE, "/api/v2/products/4"),
(Method::POST, "/api/v2/products/4/annotation-types"), (Method::POST, "/api/v2/annotation-types"),
(Method::PATCH, "/api/v2/annotation-types/9"), (Method::DELETE, "/api/v2/annotation-types/9"),
(Method::POST, "/administration/api/annotation_type/create/")] {
for (m, p) in [
(Method::POST, "/api/v2/products"),
(Method::PATCH, "/api/v2/products/4"),
(Method::DELETE, "/api/v2/products/4"),
(Method::POST, "/api/v2/products/4/annotation-types"),
(Method::POST, "/api/v2/annotation-types"),
(Method::PATCH, "/api/v2/annotation-types/9"),
(Method::DELETE, "/api/v2/annotation-types/9"),
(Method::POST, "/administration/api/annotation_type/create/"),
] {
assert!(ok(&c, m.clone(), p), "{m} {p}");
assert!(!ok(&["annotate", "images", "jobs"], m.clone(), p), "{m} {p}");
assert!(
!ok(&["annotate", "images", "jobs"], m.clone(), p),
"{m} {p}"
);
}
assert!(!ok(&c, Method::POST, "/api/v2/annotations"));
assert!(!ok(&c, Method::POST, "/api/v2/image-sets/3/images"));
Expand All @@ -155,9 +184,21 @@ mod tests {
fn annotate_and_images_are_separate() {
assert!(ok(&["annotate"], Method::POST, "/api/v2/annotations"));
assert!(ok(&["annotate"], Method::PATCH, "/api/v2/annotations/7"));
assert!(ok(&["annotate"], Method::POST, "/api/v1/annotations/annotations/"));
assert!(ok(&["annotate"], Method::POST, "/annotations/api/annotation/create/"));
assert!(!ok(&["annotate"], Method::POST, "/api/v2/image-sets/3/images"));
assert!(ok(
&["annotate"],
Method::POST,
"/api/v1/annotations/annotations/"
));
assert!(ok(
&["annotate"],
Method::POST,
"/annotations/api/annotation/create/"
));
assert!(!ok(
&["annotate"],
Method::POST,
"/api/v2/image-sets/3/images"
));
assert!(ok(&["images"], Method::POST, "/api/v2/image-sets/3/images"));
assert!(ok(&["images"], Method::POST, "/images/image/upload/3/"));
assert!(ok(&["images"], Method::DELETE, "/api/v2/images/5"));
Expand Down
19 changes: 11 additions & 8 deletions crates/exact-api/src/slides.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,12 +531,13 @@ async fn centered_snapshot(
))
}
};
let default_frame: i32 = sqlx::query_scalar("SELECT \"defaultFrame\" FROM images_image WHERE id = $1")
.bind(img.id)
.fetch_optional(&s.pool)
.await
.map_err(db_err)?
.unwrap_or(0);
let default_frame: i32 =
sqlx::query_scalar("SELECT \"defaultFrame\" FROM images_image WHERE id = $1")
.bind(img.id)
.fetch_optional(&s.pool)
.await
.map_err(db_err)?
.unwrap_or(0);
let path = img.path(&s, 1, 1).to_string_lossy().into_owned();
let st = s.slides.clone();
// the corner: Django's int(cx - w / 2)
Expand All @@ -545,7 +546,8 @@ async fn centered_snapshot(
let slide = st.slides.get(&path)?;
let (sw, sh) = slide.level_dimensions().first().copied().unwrap_or((0, 0));
let (sw, sh) = (sw as i64, sh as i64);
let mut canvas = image::RgbImage::from_pixel(w as u32, h as u32, image::Rgb([255, 255, 255]));
let mut canvas =
image::RgbImage::from_pixel(w as u32, h as u32, image::Rgb([255, 255, 255]));
// the part of the wanted region that lies inside the slide
let (ix0, iy0) = (x0.max(0), y0.max(0));
let (ix1, iy1) = ((x0 + w).min(sw), (y0 + h).min(sh));
Expand All @@ -555,7 +557,8 @@ async fn centered_snapshot(
} else {
0
};
let part = slide.read_region(ix0, iy0, 0, (ix1 - ix0) as u32, (iy1 - iy0) as u32, frame)?;
let part =
slide.read_region(ix0, iy0, 0, (ix1 - ix0) as u32, (iy1 - iy0) as u32, frame)?;
for (px, py, c) in part.enumerate_pixels() {
// transparent pixels (a slide with no data there) are white, too
let a = c[3] as u32;
Expand Down
39 changes: 23 additions & 16 deletions crates/exact-api/src/v2/access_tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
//! A token cannot make tokens: managing them needs the password or a sign-in session, and not an impersonation (an administrator who
//! impersonates somebody must not be able to mint a lasting credential in their name).

use crate::scope::SCOPES;
use crate::{
auth::{authenticate_account, require_user, AuthKind, Principal},
compat::engine::db_err,
Expand All @@ -29,7 +30,6 @@ use axum::{
};
use chrono::{DateTime, Duration, Utc};
use exact_auth::tokens::{generate_pat, hash_token};
use crate::scope::SCOPES;
use exact_db::users;
use serde::Deserialize;
use serde_json::{json, Value};
Expand Down Expand Up @@ -90,14 +90,15 @@ async fn json_of(s: &AppState, rows: Vec<Row>, with_user: bool) -> ApiResult<Vec
} else {
HashMap::new()
};
let scopes: HashMap<i64, Vec<String>> =
sqlx::query_as::<_, (i64, Vec<String>)>("SELECT token_id, scopes FROM exact_rust_token_scope WHERE token_id = ANY($1)")
.bind(&ids)
.fetch_all(&s.pool)
.await
.map_err(db_err)?
.into_iter()
.collect();
let scopes: HashMap<i64, Vec<String>> = sqlx::query_as::<_, (i64, Vec<String>)>(
"SELECT token_id, scopes FROM exact_rust_token_scope WHERE token_id = ANY($1)",
)
.bind(&ids)
.fetch_all(&s.pool)
.await
.map_err(db_err)?
.into_iter()
.collect();
let now = Utc::now();
Ok(rows
.into_iter()
Expand Down Expand Up @@ -181,7 +182,9 @@ async fn create(
let scopes = match b.scopes {
None => None,
Some(_) if b.read_only => {
return Err(bad("A read-only token cannot have scopes: it may only look."))
return Err(bad(
"A read-only token cannot have scopes: it may only look.",
))
}
Some(mut v) => {
v.sort();
Expand All @@ -205,7 +208,9 @@ async fn create(
.await
.map_err(db_err)?;
if mine.len() != teams.len() {
return Err(bad("A token can only be restricted to teams you belong to."));
return Err(bad(
"A token can only be restricted to teams you belong to.",
));
}
}
let (token, prefix) = generate_pat();
Expand Down Expand Up @@ -266,11 +271,13 @@ async fn revoke(s: &AppState, id: i64, owner: Option<i64>) -> ApiResult<StatusCo
.await
.map_err(db_err)?;
} else {
sqlx::query("DELETE FROM users_personalaccesstoken_teams WHERE personalaccesstoken_id = $1")
.bind(id)
.execute(&s.pool)
.await
.map_err(db_err)?;
sqlx::query(
"DELETE FROM users_personalaccesstoken_teams WHERE personalaccesstoken_id = $1",
)
.bind(id)
.execute(&s.pool)
.await
.map_err(db_err)?;
sqlx::query("DELETE FROM users_personalaccesstoken WHERE id = $1")
.bind(id)
.execute(&s.pool)
Expand Down
5 changes: 4 additions & 1 deletion crates/exact-api/src/v2/annotation_writes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,10 @@ pub async fn create_h(
};
// a global annotation exists once per image and type (and user in competitive sets), and per frame when it names one: it is
// switched on again, not duplicated
let frame: Option<String> = vec_value.get("frame").and_then(Value::as_i64).map(|f| f.to_string());
let frame: Option<String> = vec_value
.get("frame")
.and_then(Value::as_i64)
.map(|f| f.to_string());
let existing: Option<(i64, bool)> = if atype.vector_type == vector::GLOBAL {
let competitive = sqlx::query_scalar::<_, i32>(
"SELECT collaboration_type FROM images_imageset WHERE id = $1",
Expand Down
Loading
Loading