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
7 changes: 7 additions & 0 deletions atomic-cli/src/commands/workspace/grant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,7 @@ fn subject_label(
atomic_teams::GrantSubjectType::User => {
format!("user {}", user_id.as_deref().unwrap_or("?"))
}
atomic_teams::GrantSubjectType::Everyone => "everyone".to_string(),
}
}

Expand Down Expand Up @@ -488,4 +489,10 @@ mod tests {
);
assert_eq!(label, "user 550e8400-e29b-41d4-a716-446655440000");
}

#[test]
fn subject_label_everyone() {
let label = subject_label(atomic_teams::GrantSubjectType::Everyone, &None, &None);
assert_eq!(label, "everyone");
}
}
13 changes: 7 additions & 6 deletions atomic-teams/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -450,10 +450,11 @@ async fn team_member_example(client: &StorageClient) -> TeamsResult<()> {

### Grants API

Grants bind a subject (user or team) to a relation (read, write, admin,
owner) on a resource (org or workspace). The server uses a Zanzibar-style
ReBAC engine with structural inheritance — an org owner automatically has
admin access to all workspaces within the org.
Grants bind a subject to a relation (read, write, admin, owner) on a resource
(org or workspace). Grant mutations target a concrete user or team; list
responses can also contain `Everyone` for public/wildcard grants. The server
uses a Zanzibar-style ReBAC engine with structural inheritance — an org owner
automatically has admin access to all workspaces within the org.

```rust
use atomic_teams::{grant, GrantInfo, GrantRelation, GrantSubjectType, TeamsResult};
Expand Down Expand Up @@ -809,7 +810,7 @@ async fn handle_errors(client: &atomic_remote::StorageClient) {
| `TeamRole` | `Maintainer`, `Contributor`, `Collaborator`, `Consumer` | Team membership |
| `TeamVisibility` | `Visible`, `Secret` | Team creation/update |
| `GrantRelation` | `Read`, `Write`, `Admin`, `Owner` | Grant operations |
| `GrantSubjectType` | `User`, `Team` | Grant operations |
| `GrantSubjectType` | `User`, `Team`, `Everyone` | Grant operations and responses |

All enums implement `Display`, `FromStr`, `Serialize`, and `Deserialize`.
String representations are lowercase (`"owner"`, `"admin"`, `"maintainer"`, `"contributor"`, etc.).
Expand Down Expand Up @@ -866,4 +867,4 @@ cargo run -p atomic-cli --no-default-features -- --help | grep -E "org|team"

## License

Dual-licensed under MIT and Apache 2.0, same as the Atomic project.
Dual-licensed under MIT and Apache 2.0, same as the Atomic project.
71 changes: 56 additions & 15 deletions atomic-teams/src/grant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,22 @@ use uuid::Uuid;

use atomic_remote::storage::StorageClient;

use crate::error::{map_remote_error, TeamsResult};
use crate::error::{map_remote_error, TeamsError, TeamsResult};
use crate::types::{AddGrantRequest, GrantInfo, GrantRelation, GrantSubjectType};

/// Ensure a grant mutation targets a concrete user or team.
///
/// `Everyone` is emitted by Storage when listing public grants, but the
/// mutation endpoints require a non-null user or team UUID.
fn validate_mutation_subject(subject_type: GrantSubjectType) -> TeamsResult<()> {
match subject_type {
GrantSubjectType::User | GrantSubjectType::Team => Ok(()),
GrantSubjectType::Everyone => Err(TeamsError::InvalidInput(
"grant mutations require a user or team subject".to_string(),
)),
}
}

// ---------------------------------------------------------------------------
// Organization grants
// ---------------------------------------------------------------------------
Expand All @@ -34,9 +47,9 @@ use crate::types::{AddGrantRequest, GrantInfo, GrantRelation, GrantSubjectType};
///
/// # Errors
///
/// Returns [`TeamsError::OrgNotFound`](crate::error::TeamsError::OrgNotFound)
/// Returns [`TeamsError::OrgNotFound`]
/// if the org does not exist, or
/// [`TeamsError::PermissionDenied`](crate::error::TeamsError::PermissionDenied)
/// [`TeamsError::PermissionDenied`]
/// if the caller lacks access.
pub async fn list_org_grants(
client: &StorageClient,
Expand All @@ -56,17 +69,20 @@ pub async fn list_org_grants(
///
/// # Errors
///
/// Returns [`TeamsError::AlreadyExists`](crate::error::TeamsError::AlreadyExists)
/// Returns [`TeamsError::AlreadyExists`]
/// if the grant already exists, or
/// [`TeamsError::PermissionDenied`](crate::error::TeamsError::PermissionDenied)
/// if the caller is not an org owner.
/// [`TeamsError::PermissionDenied`]
/// if the caller is not an org owner. Returns
/// [`TeamsError::InvalidInput`] when
/// `subject_type` is [`GrantSubjectType::Everyone`].
pub async fn add_org_grant(
client: &StorageClient,
org_slug: &str,
subject_type: GrantSubjectType,
subject_id: Uuid,
relation: GrantRelation,
) -> TeamsResult<GrantInfo> {
validate_mutation_subject(subject_type)?;
let path = format!("/orgs/{org_slug}/grants");
let body = AddGrantRequest {
subject_type,
Expand All @@ -87,16 +103,19 @@ pub async fn add_org_grant(
///
/// # Errors
///
/// Returns [`TeamsError::OrgNotFound`](crate::error::TeamsError::OrgNotFound)
/// Returns [`TeamsError::OrgNotFound`]
/// if the org does not exist, or
/// [`TeamsError::PermissionDenied`](crate::error::TeamsError::PermissionDenied)
/// if the caller is not an org owner.
/// [`TeamsError::PermissionDenied`]
/// if the caller is not an org owner. Returns
/// [`TeamsError::InvalidInput`] when
/// `subject_type` is [`GrantSubjectType::Everyone`].
pub async fn revoke_org_grant(
client: &StorageClient,
org_slug: &str,
subject_type: GrantSubjectType,
subject_id: Uuid,
) -> TeamsResult<()> {
validate_mutation_subject(subject_type)?;
let st = subject_type.to_string();
let path = format!("/orgs/{org_slug}/grants/{st}/{subject_id}");
client
Expand All @@ -113,7 +132,7 @@ pub async fn revoke_org_grant(
///
/// # Errors
///
/// Returns [`TeamsError::PermissionDenied`](crate::error::TeamsError::PermissionDenied)
/// Returns [`TeamsError::PermissionDenied`]
/// if the caller lacks read access, or a not-found error if the workspace
/// doesn't exist.
pub async fn list_workspace_grants(
Expand All @@ -134,17 +153,20 @@ pub async fn list_workspace_grants(
///
/// # Errors
///
/// Returns [`TeamsError::AlreadyExists`](crate::error::TeamsError::AlreadyExists)
/// Returns [`TeamsError::AlreadyExists`]
/// if the grant already exists, or
/// [`TeamsError::PermissionDenied`](crate::error::TeamsError::PermissionDenied)
/// if the caller is not a workspace admin.
/// [`TeamsError::PermissionDenied`]
/// if the caller is not a workspace admin. Returns
/// [`TeamsError::InvalidInput`] when
/// `subject_type` is [`GrantSubjectType::Everyone`].
pub async fn add_workspace_grant(
client: &StorageClient,
workspace_slug: &str,
subject_type: GrantSubjectType,
subject_id: Uuid,
relation: GrantRelation,
) -> TeamsResult<crate::types::WorkspaceGrantInfo> {
validate_mutation_subject(subject_type)?;
let path = format!("/workspaces/{workspace_slug}/grants");
let body = AddGrantRequest {
subject_type,
Expand All @@ -165,15 +187,18 @@ pub async fn add_workspace_grant(
///
/// # Errors
///
/// Returns [`TeamsError::PermissionDenied`](crate::error::TeamsError::PermissionDenied)
/// Returns [`TeamsError::PermissionDenied`]
/// if the caller is not a workspace admin, or a not-found error if the
/// workspace doesn't exist.
/// workspace doesn't exist. Returns
/// [`TeamsError::InvalidInput`] when
/// `subject_type` is [`GrantSubjectType::Everyone`].
pub async fn revoke_workspace_grant(
client: &StorageClient,
workspace_slug: &str,
subject_type: GrantSubjectType,
subject_id: Uuid,
) -> TeamsResult<()> {
validate_mutation_subject(subject_type)?;
let st = subject_type.to_string();
let path = format!("/workspaces/{workspace_slug}/grants/{st}/{subject_id}");
client
Expand Down Expand Up @@ -216,6 +241,22 @@ mod tests {
assert!(json.contains("\"relation\":\"read\""), "got: {json}");
}

#[test]
fn mutation_subject_rejects_everyone() {
let error = validate_mutation_subject(GrantSubjectType::Everyone).unwrap_err();
assert!(matches!(error, TeamsError::InvalidInput(_)));
assert_eq!(
error.to_string(),
"Invalid input: grant mutations require a user or team subject"
);
}

#[test]
fn mutation_subject_accepts_users_and_teams() {
assert!(validate_mutation_subject(GrantSubjectType::User).is_ok());
assert!(validate_mutation_subject(GrantSubjectType::Team).is_ok());
}

#[test]
fn org_revoke_path_format() {
let slug = "acme";
Expand Down
46 changes: 43 additions & 3 deletions atomic-teams/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,13 +172,19 @@ pub enum GrantSubjectType {
User,
/// A team within the organization.
Team,
/// Every caller, returned by the server for public/wildcard grants.
///
/// Grant mutation helpers reject this response-only subject because the
/// Storage API only accepts concrete user or team UUIDs.
Everyone,
}

impl fmt::Display for GrantSubjectType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::User => write!(f, "user"),
Self::Team => write!(f, "team"),
Self::Everyone => write!(f, "everyone"),
}
}
}
Expand All @@ -190,6 +196,7 @@ impl FromStr for GrantSubjectType {
match s.to_lowercase().as_str() {
"user" => Ok(Self::User),
"team" => Ok(Self::Team),
"everyone" => Ok(Self::Everyone),
other => Err(format!("unknown grant subject type: {other}")),
}
}
Expand Down Expand Up @@ -352,7 +359,7 @@ pub struct TeamMemberInfo {
pub struct GrantInfo {
/// Unique identifier.
pub id: Uuid,
/// Whether the subject is a user or team (`"user"` or `"team"`).
/// Whether the subject is a user, team, or everyone.
pub subject_type: GrantSubjectType,
/// The subject's identity or team ID (absent for wildcard/everyone grants).
pub subject_id: Option<Uuid>,
Expand All @@ -374,7 +381,7 @@ pub struct GrantInfo {
pub struct WorkspaceGrantInfo {
/// Unique identifier of the ReBAC tuple.
pub id: Uuid,
/// Whether the subject is a user or team (`"user"` or `"team"`).
/// Whether the subject is a user, team, or everyone.
pub subject_type: GrantSubjectType,
/// The subject's identity or team UUID (absent for wildcard/everyone grants).
pub subject_id: Option<Uuid>,
Expand Down Expand Up @@ -569,7 +576,11 @@ mod tests {

#[test]
fn grant_subject_type_display_roundtrip() {
for st in [GrantSubjectType::User, GrantSubjectType::Team] {
for st in [
GrantSubjectType::User,
GrantSubjectType::Team,
GrantSubjectType::Everyone,
] {
let s = st.to_string();
let parsed: GrantSubjectType = s.parse().unwrap();
assert_eq!(parsed, st);
Expand Down Expand Up @@ -743,6 +754,29 @@ mod tests {
assert!(de.granted_by.is_some());
}

#[test]
fn workspace_grant_info_deserializes_public_everyone_grant() {
// Public workspaces use a wildcard grant. Its subject has no UUID,
// and Storage reports the subject type explicitly as `everyone`.
let json = r#"{
"id": "550e8400-e29b-41d4-a716-446655440000",
"subject_type": "everyone",
"subject_id": null,
"subject_relation": null,
"relation": "read",
"object_type": "workspace",
"object_id": "550e8400-e29b-41d4-a716-446655440002",
"granted_at": "2024-01-01T00:00:00Z",
"granted_by": null
}"#;

let grant: WorkspaceGrantInfo = serde_json::from_str(json).unwrap();
assert_eq!(grant.subject_type, GrantSubjectType::Everyone);
assert!(grant.subject_id.is_none());
assert_eq!(grant.relation, GrantRelation::Read);
assert_eq!(grant.subject_type.to_string(), "everyone");
}

#[test]
fn domain_alias_info_serde_roundtrip() {
let info = DomainAliasInfo {
Expand Down Expand Up @@ -892,6 +926,9 @@ mod tests {

let json = serde_json::to_string(&GrantSubjectType::Team).unwrap();
assert_eq!(json, "\"team\"");

let json = serde_json::to_string(&GrantSubjectType::Everyone).unwrap();
assert_eq!(json, "\"everyone\"");
}

#[test]
Expand All @@ -904,5 +941,8 @@ mod tests {

let rel: GrantRelation = serde_json::from_str("\"write\"").unwrap();
assert_eq!(rel, GrantRelation::Write);

let subject: GrantSubjectType = serde_json::from_str("\"everyone\"").unwrap();
assert_eq!(subject, GrantSubjectType::Everyone);
}
}
Loading