Skip to content
Open
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
6 changes: 4 additions & 2 deletions app/src/auth/invitations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,14 +135,16 @@ pub async fn may_send(org_id: i64, address: Option<&str>) -> laravel::Result<Res
Ok(Ok(()))
}

/// The organization by slug and the person's role there; a 404 when they aren't a member. Staff are no exception:
/// The organization by slug (its current one first, then one it had before, as `Organization::by_slug`) and the
/// person's role there; a 404 when they aren't a member. Staff are no exception:
/// their tools are the admin MCP's, with its audit log, never the customer pages.
pub(crate) async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role)> {
let user_id = user.id;
let row = db::query!(
"SELECT o.id, o.name, m.role FROM organizations o \
LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} WHERE o.id IN (SELECT id FROM organizations WHERE slug = {slug} UNION ALL \
SELECT organization_id FROM previous_organization_slugs WHERE slug = {slug})"
SELECT organization_id FROM previous_organization_slugs WHERE slug = {slug}) \
ORDER BY (o.slug = {slug}) DESC LIMIT 1"
)
.select_one()
.await?
Expand Down
56 changes: 47 additions & 9 deletions app/src/auth/orgs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,17 +305,37 @@ pub async fn rename(org_id: i64, slug: &str) -> laravel::Result<Organization> {
Ok(renamed)
}

/// `PATCH /api/ui/orgs/{org}` (admins): its slug, its name and the settings new projects start with; fields left out stay as
/// they are. Existing projects keep their own settings.
pub async fn update(
Authenticated(user): Authenticated<User>,
Params(slug): Params<String>,
Valid(p): Valid<UpdateInput>,
) -> laravel::Result<Json<Value>> {
let (org_id, _, role) = super::invitations::org_role(&user, &slug).await?;
/// What an update changes; fields left out stay as they are.
#[derive(Debug, Default)]
pub struct Change {
/// The display name.
pub name: Option<String>,
/// A new slug: the old one keeps working ([`rename`]).
pub slug: Option<String>,
/// The diff threshold a new project starts with, 0 to 1.
pub project_threshold: Option<f64>,
/// Whether a new project comments on pull requests whose builds are unchanged.
pub project_comment_when_unchanged: Option<bool>,
}

/// Refuse anyone but an organization's admins: what the settings page, the API and MCP all say.
///
/// # Errors
/// A 403 for anyone else.
pub fn need_admin(role: Role) -> laravel::Result<()> {
if role < Role::Admin {
return Err(laravel::abort_with(403, "only admins can change the organization's settings"));
}
Ok(())
}

/// Change an organization's name, slug or the settings new projects start with, for its settings page, the API and
/// MCP (the caller checks it's an admin, [`need_admin`]). 422 for a name, threshold or slug it refuses, 409 for a
/// slug that's taken.
///
/// # Errors
/// Those, and database errors.
pub async fn change(org_id: i64, p: Change) -> laravel::Result<Organization> {
let name = p.name.as_deref().map(str::trim).map(str::to_string);
if let Some(name) = &name
&& (name.is_empty() || name.chars().count() > MAX_NAME)
Expand All @@ -338,7 +358,25 @@ pub async fn update(
)
.update()
.await?;
let org = Organization::find_or_fail(org_id).await?;
Organization::find_or_fail(org_id).await
}

/// `PATCH /api/ui/orgs/{org}` (admins): its slug, its name and the settings new projects start with; fields left out stay as
/// they are. Existing projects keep their own settings.
pub async fn update(
Authenticated(user): Authenticated<User>,
Params(slug): Params<String>,
Valid(p): Valid<UpdateInput>,
) -> laravel::Result<Json<Value>> {
let (org_id, _, role) = super::invitations::org_role(&user, &slug).await?;
need_admin(role)?;
let change = Change {
name: p.name,
slug: p.slug,
project_threshold: p.project_threshold,
project_comment_when_unchanged: p.project_comment_when_unchanged,
};
let org = self::change(org_id, change).await?;
Ok(Json(json!({
"slug": org.slug, "name": org.name,
"project_defaults": {
Expand Down
22 changes: 22 additions & 0 deletions app/src/http/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

pub mod builds;
pub mod downloads;
pub mod organizations;
pub mod support;

use axum::extract::FromRequestParts;
Expand All @@ -22,6 +23,7 @@ pub fn routes(route: &mut Router) {
route.get("/v1/whoami", crate::auth::whoami);
builds::routes(route);
route.post("/v1/support/feedback", support::feedback);
organizations::routes(route);
downloads::routes(route);
crate::auth::device::api_routes(route);
super::live::api_routes(route);
Expand Down Expand Up @@ -62,6 +64,26 @@ impl ApiError {
}
}

#[must_use]
pub fn forbidden(message: impl Into<String>) -> Self {
Self { status: StatusCode::FORBIDDEN, body: json!({ "error": "forbidden", "description": message.into() }) }
}

/// A handler's refusal (`laravel::abort_with`) with its status and message; a server error as one.
#[must_use]
pub fn refused(e: laravel::Error) -> Self {
let status = e.status();
let kind = match status {
StatusCode::FORBIDDEN => "forbidden",
StatusCode::NOT_FOUND => return Self::not_found(),
StatusCode::CONFLICT => "conflict",
StatusCode::UNPROCESSABLE_ENTITY => "unprocessable_entity",
s if s.is_client_error() => "Bad Request",
_ => return Self::server(&e),
};
Self { status, body: json!({ "error": kind, "description": e.to_string() }) }
}

#[must_use]
pub fn not_found() -> Self {
Self {
Expand Down
106 changes: 106 additions & 0 deletions app/src/http/api/organizations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
//! `GET` and `PATCH /api/v1/organizations/{org}`: an organization as MCP's `get_organization` answers it, and its name
//! and slug changed by an admin with the settings page's rules ([`crate::auth::orgs::change`]). `{org}` may be a slug
//! the organization had before a rename.

use axum::response::{IntoResponse, Response};
use serde::Deserialize;
use serde_json::Value;

use super::ApiError;
use crate::auth::{Principal, Role};
use crate::mcp::VisualCi;
use crate::models::{Organization, Project};

pub fn routes(route: &mut laravel::prelude::Router) {
route.get("/v1/organizations/{org}", show);
route.patch("/v1/organizations/{org}", update);
}

/// The fields `PATCH` takes; any other is refused (422, as [`super::Body`] does).
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UpdateBody {
#[serde(default)]
name: Option<String>,
#[serde(default)]
slug: Option<String>,
}

fn unauthorized() -> ApiError {
ApiError::unauthorized("a personal access token or a project token is required")
}

/// The organization and the caller's role there (`project` for a project token of one of its projects); a 404 for
/// anyone who can't see it.
async fn find(principal: &Principal, slug: &str) -> Result<(Organization, String), ApiError> {
match principal {
Principal::User { user, .. } => {
let (id, _, role) = crate::auth::invitations::org_role(user, slug).await.map_err(ApiError::refused)?;
Ok((Organization::find_or_fail(id).await?, role.as_str().to_string()))
}
Principal::Project { project_id, .. } => {
let org = Organization::by_slug(slug).await?.ok_or_else(ApiError::not_found)?;
let project = Project::find_live(*project_id).await?.ok_or_else(ApiError::not_found)?;
if project.organization_id != org.id {
return Err(ApiError::not_found());
}
Ok((org, "project".to_string()))
}
}
}

async fn answer(org: &Organization, role: &str, principal: &Principal) -> Result<axum::Json<Value>, ApiError> {
VisualCi::organization_json(org, role, principal)
.await
.map(axum::Json)
.map_err(|e| ApiError::server(&laravel::Error::msg(e.message.to_string())))
}

/// `GET /api/v1/organizations/{org}`: the organization, as MCP's `get_organization` answers it.
pub async fn show(
principal: Result<Principal, laravel::Error>,
laravel::prelude::Params(slug): laravel::prelude::Params<String>,
) -> Response {
respond(show_org(principal, &slug).await)
}

async fn show_org(principal: Result<Principal, laravel::Error>, slug: &str) -> Result<axum::Json<Value>, ApiError> {
let principal = principal.map_err(|_| unauthorized())?;
let (org, role) = find(&principal, slug).await?;
answer(&org, &role, &principal).await
}

fn respond(r: Result<axum::Json<Value>, ApiError>) -> Response {
match r {
Ok(json) => json.into_response(),
Err(e) => e.into_response(),
}
}

/// `PATCH /api/v1/organizations/{org}` (admins, with a personal token): its name and slug; fields left out stay as
/// they are. A new slug renames it, and the old one keeps working.
pub async fn update(
principal: Result<Principal, laravel::Error>,
laravel::prelude::Params(slug): laravel::prelude::Params<String>,
body: axum::body::Bytes,
) -> Response {
respond(update_org(principal, &slug, &body).await)
}

async fn update_org(
principal: Result<Principal, laravel::Error>,
slug: &str,
body: &[u8],
) -> Result<axum::Json<Value>, ApiError> {
let principal = principal.map_err(|_| unauthorized())?;
// Read after the token: a request without one is a 401, whatever its body.
let body: UpdateBody = serde_json::from_slice(body).map_err(|e| ApiError::unreadable(&e))?;
if !matches!(principal, Principal::User { .. }) {
return Err(ApiError::forbidden("changing an organization needs a personal access token, not a project token"));
}
let (org, role) = find(&principal, slug).await?;
crate::auth::orgs::need_admin(Role::parse(&role).unwrap_or(Role::Read)).map_err(ApiError::refused)?;
let change = crate::auth::orgs::Change { name: body.name, slug: body.slug, ..Default::default() };
let org = crate::auth::orgs::change(org.id, change).await.map_err(ApiError::refused)?;
answer(&org, &role, &principal).await
}
12 changes: 12 additions & 0 deletions app/src/mcp/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,18 @@ pub struct CreateOrgArgs {
pub name: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct UpdateOrgArgs {
/// The organization's slug (its current one, or one it had before).
pub org: String,
/// A new display name. Leave it out to keep it.
#[serde(default)]
pub name: Option<String>,
/// A new slug: lowercase letters, digits and dashes, not a reserved word. Leave it out to keep it.
#[serde(default)]
pub slug: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct CreateProjectArgs {
pub org: String,
Expand Down
Loading
Loading