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
6 changes: 6 additions & 0 deletions crates/fctl-control/migrations/0077_workspace_sign_in.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- A workspace's own sign-in requirement (#618, ADR 0103): its members who
-- are in it as an address at one of the rule's domains open it only with a
-- sign-in made with its provider as such an address. JSON of a
-- fctl_proto::api::SignInRule ({"domains": [...], "provider": "google",
-- "passkeys": false}); NULL, the default: none.
ALTER TABLE workspaces ADD COLUMN sign_in TEXT;
2 changes: 1 addition & 1 deletion crates/fctl-control/src/api/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -669,7 +669,7 @@ async fn start(ctx: &Ctx, user: &UserRow, slot: Slot) -> AppResult<Export> {
let open: Vec<String> = crate::workspaces::mine(&ctx.db, &user.id)
.await?
.into_iter()
.filter(|w| !user.blocked_by(&settings, w.require_two_factor))
.filter(|w| !w.closed_to(user, &settings))
.map(|w| w.id)
.collect();
let mine_open =
Expand Down
2 changes: 1 addition & 1 deletion crates/fctl-control/src/api/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -627,7 +627,7 @@ async fn login_runners(ctx: &Ctx, user: &UserRow) -> AppResult<Vec<String>> {
let open: Vec<String> = crate::workspaces::mine(&ctx.db, &user.id)
.await?
.into_iter()
.filter(|w| !crate::workspaces::blocked_for(ctx, user, w.require_two_factor))
.filter(|w| !w.closed_to(user, &ctx.settings()))
.map(|w| w.id)
.collect();
let mine = |r: &R| r.owner.as_deref() == Some(user.id.as_str());
Expand Down
2 changes: 1 addition & 1 deletion crates/fctl-control/src/api/projects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1212,7 +1212,7 @@ pub async fn github_info(ctx: &Ctx) -> AppResult<Response> {
let open: Vec<String> = ws::mine(&ctx.db, &user.id)
.await?
.into_iter()
.filter(|w| !ws::blocked_for(ctx, user, w.require_two_factor))
.filter(|w| !w.closed_to(user, &ctx.settings()))
.filter(|w| reached.as_ref().is_none_or(|r| r.contains(&w.id)))
.map(|w| w.id)
.collect();
Expand Down
24 changes: 18 additions & 6 deletions crates/fctl-control/src/api/runners.rs
Original file line number Diff line number Diff line change
Expand Up @@ -493,22 +493,34 @@ pub async fn rotate_token(ctx: &mut Ctx, id: &str) -> AppResult<Response> {
name: String,
#[serde(deserialize_with = "crate::db::int_bool")]
require_two_factor: bool,
#[serde(default)]
sign_in: Option<String>,
}
let served: Vec<Served> = q(
&ctx.db,
"SELECT w.name AS name, w.require_two_factor AS require_two_factor FROM runner_workspaces rw \
concat!(
"SELECT w.name AS name, w.require_two_factor AS require_two_factor, ",
crate::workspace_sign_in!("w", "m.email"),
" AS sign_in FROM runner_workspaces rw \
JOIN workspaces w ON w.id = rw.workspace_id \
JOIN workspace_members m ON m.workspace_id = rw.workspace_id AND m.user_id = ? \
WHERE rw.runner_id = ?",
WHERE rw.runner_id = ?"
),
&[s(&user_id), s(id)],
)?
.all()
.await?;
let user = ctx.user()?;
if let Some(closed) = served
.iter()
.find(|w| crate::workspaces::blocked_for(ctx, user, w.require_two_factor))
{
if let Some(closed) = served.iter().find(|w| {
crate::workspaces::blocked_for(ctx, user, w.require_two_factor, w.sign_in.as_deref())
}) {
if user.sign_in_blocked(closed.sign_in.as_deref()) {
return Err(forbidden(&crate::workspaces::sign_in_refusal(
&closed.name,
closed.sign_in.as_deref(),
"replace the runner's token, as it runs its sessions",
)));
}
return Err(forbidden(&format!(
"This runner runs the sessions of {}, which requires two-factor sign-in: set it up in Settings before you replace the runner's token.",
closed.name
Expand Down
5 changes: 3 additions & 2 deletions crates/fctl-control/src/api/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,12 @@ pub async fn search(ctx: &Ctx, req: &Request) -> AppResult<Response> {
let mut scopes: BTreeMap<String, Scope> = BTreeMap::new();
let mut sql = format!(
"SELECT p.id, m.role AS member_role, w.id AS workspace_id, w.base_role AS workspace_base_role, \
w.require_two_factor AS workspace_two_factor, wm.role AS workspace_role \
w.require_two_factor AS workspace_two_factor, {} AS workspace_sign_in, wm.role AS workspace_role \
FROM projects p JOIN workspaces w ON w.id = p.workspace_id \
LEFT JOIN workspace_members wm ON wm.workspace_id = p.workspace_id AND wm.user_id = ?1 \
LEFT JOIN project_members m ON m.project_id = p.id AND m.user_id = ?1 \
WHERE {PROJECT_VISIBLE}"
WHERE {PROJECT_VISIBLE}",
crate::workspace_sign_in!()
);
let mut params = vec![s(&user.id)];
if let Some(w) = &workspace {
Expand Down
91 changes: 80 additions & 11 deletions crates/fctl-control/src/api/workspaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ async fn live(ctx: &Ctx) -> LiveRunners {
async fn respond(ctx: &Ctx, id: &str) -> AppResult<Workspace> {
let a = ws::load(ctx, id).await?;
let live = live(ctx).await;
Ok(a.row.to_workspace(&ctx.settings(), a.blocked, &live.online))
Ok(a.row
.to_workspace(&ctx.settings(), ctx.user()?, &live.online))
}

/// `GET /api/v1/workspaces`.
Expand All @@ -62,11 +63,7 @@ pub async fn list(ctx: &Ctx) -> AppResult<Response> {
workspaces: rows
.iter()
.map(|r| {
let mut w = r.to_workspace(
&settings,
ws::blocked_for(ctx, user, r.require_two_factor),
&live.online,
);
let mut w = r.to_workspace(&settings, user, &live.online);
// A limited token reaches projects and sessions alone: not
// the workspace's people, GitHub accounts or its person's
// Claude connections (`fctl_domain::limits`).
Expand All @@ -81,7 +78,10 @@ pub async fn list(ctx: &Ctx) -> AppResult<Response> {
.collect(),
invitations: invitations
.iter()
.map(|i| i.to_invitation(ws::blocked_for(ctx, user, i.require_two_factor)))
// Its two-factor requirement alone, which the invitation names:
// accepting it refuses, saying so, where its sign-in requirement
// closes it to this sign-in.
.map(|i| i.to_invitation(ws::blocked_for(ctx, user, i.require_two_factor, None)))
.collect(),
limit: settings.max_workspaces,
unlimited: policy::workspace_limit(user.role(), &settings).is_none(),
Expand Down Expand Up @@ -218,7 +218,25 @@ pub async fn get(ctx: &Ctx, id: &str) -> AppResult<Response> {
pub async fn update(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Response> {
let body: UpdateWorkspaceRequest = http::body(req).await?;
let a = ws::load(ctx, id).await?;
a.require_admin()?;
// Its primary admin may lift or change its sign-in requirement while it
// closes the workspace to them, and only that: where nobody can meet
// it any more (Google sign-in no longer set up, their Google accounts
// closed), the workspace would stay closed to everyone otherwise.
// Requiring less still takes confirming it's them, below.
let lifting = a.sign_in_blocked
&& a.role == Some(WorkspaceRole::Owner)
&& body.sign_in.is_some()
&& body
== UpdateWorkspaceRequest {
sign_in: body.sign_in.clone(),
..UpdateWorkspaceRequest::default()
}
&& !ctx
.user()?
.blocked_by(&ctx.settings(), a.row.require_two_factor, None);
if !lifting {
a.require_admin()?;
}
let user = ctx.user()?.clone();
let name = body.name.as_deref().map(policy::name).transpose()?;
let slug = match body.slug.as_deref() {
Expand Down Expand Up @@ -262,13 +280,51 @@ pub async fn update(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Res
}
if body.require_two_factor == Some(true)
&& !a.row.require_two_factor
&& user.blocked_by(&ctx.settings(), true)
&& user.blocked_by(&ctx.settings(), true, None)
{
return Err(AppError(ApiError::new(
ErrorCode::Conflict,
"Set up two-factor sign-in yourself first (Settings → Security): the workspace would close to you too.",
)));
}
// Its own sign-in requirement: none that would close it to the admin
// who saves it (they sign in with the provider first, which shows it
// works for them), and letting anyone in another way is sensitive.
let sign_in = match &body.sign_in {
Some(rule) => Some(
fctl_domain::sign_in::check_workspace_rule(rule, &crate::sign_in::providers(&ctx.cfg))
.map_err(AppError)?,
),
None => None,
};
if let Some(next) = &sign_in {
if fctl_domain::verify::workspace_sign_in_relaxed(
a.row.sign_in_rule().as_ref(),
next.as_ref(),
) {
ctx.verified(Sensitive::RelaxWorkspaceSignIn)?;
}
if let Some(rule) = next {
let mine = fctl_domain::sign_in::domain_of(a.row.email.as_deref().unwrap_or_default());
let covers = mine.is_some_and(|d| rule.domains.contains(&d));
if covers
Comment thread
fctl-review[bot] marked this conversation as resolved.
Resolved
&& user
.request_sign_in
.as_ref()
.is_some_and(|how| !fctl_domain::sign_in::meets(rule, how))
{
return Err(AppError(ApiError::new(
ErrorCode::Conflict,
format!(
"This would close {} to you: you're in it as {}, and signed in another way. Sign in with {} as that address first, which shows it works for you, then require it.",
a.row.name,
a.row.email.as_deref().unwrap_or_default(),
crate::sign_in::provider_name(&rule.provider)
),
)));
}
}
}
let updated = q(
&ctx.db,
"UPDATE workspaces SET name = COALESCE(?, name), slug = COALESCE(?, slug), color = COALESCE(?, color), \
Expand Down Expand Up @@ -301,6 +357,18 @@ pub async fn update(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Res
if updated.is_ok() && body.autopilots == Some(false) {
crate::autopilots::pause_workspace(&ctx.db, a.id(), &user.id, ctx.now).await?;
}
if updated.is_ok()
&& let Some(next) = &sign_in
{
let json = next.as_ref().map(serde_json::to_string).transpose()?;
q(
&ctx.db,
"UPDATE workspaces SET sign_in = ? WHERE id = ?",
&[os(json.as_deref()), s(a.id())],
)?
.run()
.await?;
}
if let Err(e) = updated {
if let Some(sl) = &slug
&& slugs::taken(&ctx.db, Of::Workspace, sl, Some(a.id())).await?
Expand All @@ -318,7 +386,8 @@ pub async fn update(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Res
Some(a.id()),
Some(serde_json::to_value(&body)?),
);
// Who sees what changes with the base role and two-factor.
// Who sees what changes with the base role, two-factor and its sign-in
// requirement.
ws::changed(ctx, ws::member_ids(&ctx.db, a.id()).await?);
http::ok(&respond(ctx, a.id()).await?)
}
Expand Down Expand Up @@ -1315,7 +1384,7 @@ impl Viewer {
let open: Vec<ws::WorkspaceRow> = ws::mine(&ctx.db, &user.id)
.await?
.into_iter()
.filter(|w| !ws::blocked_for(ctx, user, w.require_two_factor))
.filter(|w| !w.closed_to(user, &ctx.settings()))
.collect();
Ok(Self {
user_id: user.id.clone(),
Expand Down
11 changes: 9 additions & 2 deletions crates/fctl-control/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,9 +364,13 @@ pub async fn by_token_id(db: &D1Database, token_id: &str, now: i64) -> AppResult
f.user.has_password(),
f.user.factors(),
);
// The token's own sign-in, which workspaces' own requirements
// check, as `authenticate` gives a request.
let mut user = f.user;
user.request_sign_in = Some(how);
(!setup_required).then(|| Holder {
limits: Limits::parse(f.scope.as_deref()),
user: f.user,
user,
settings,
})
}))
Expand Down Expand Up @@ -558,8 +562,11 @@ pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> {
);
// However it comes: in a cookie, a limited token stays limited.
let limits = Limits::parse(found.scope.as_deref());
// A person's own sign-in: what workspaces' own requirements check.
let mut user = found.user;
user.request_sign_in = Some(how.clone());
ctx.auth = Some(Authed {
user: found.user,
user,
token_id: found.token_id,
kind,
via_cookie,
Expand Down
4 changes: 3 additions & 1 deletion crates/fctl-control/src/ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,10 @@ impl Authed {
verified_at: Option<i64>,
how: SignedIn,
) -> Self {
let mut user = user.clone();
user.request_sign_in = Some(how.clone());
Self {
user: user.clone(),
user,
token_id,
kind: TokenKind::Web,
via_cookie: true,
Expand Down
44 changes: 32 additions & 12 deletions crates/fctl-control/src/do_fleet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4031,22 +4031,42 @@ impl FleetObject {
if sockets.is_empty() {
continue;
}
let Ok(Some(user)) = user_row(&db, user_id).await else {
let Ok(Some(person)) = user_row(&db, user_id).await else {
continue;
};
let ident = match crate::workspaces::feed_identity(&db, &user, &settings).await {
Ok(i) => i,
Err(e) => {
worker::console_error!("feed identity: {}", e.0.message);
continue;
}
};
let messages = self.view_changed(&ident).await;
for ws in sockets {
// Each keeps the token it was opened with, checked as before.
// Each keeps the token it was opened with, checked as before,
// and sees what its sign-in opens: a workspace's own sign-in
// requirement may close it to one of their browsers and not
// another.
let old = ws.deserialize_attachment::<FeedIdentity>().ok().flatten();
let mut ident = ident.clone();
ident.token_id = old.as_ref().and_then(|o| o.token_id.clone());
let token_id = old.as_ref().and_then(|o| o.token_id.clone());
let mut user = person.clone();
if let Some(t) = &token_id {
match crate::auth::by_token_id(&db, t, now_ms()).await {
Ok(Some(h)) if h.user.id == *user_id => {
user.request_sign_in = h.user.request_sign_in;
}
Ok(_) => {
let _ = ws.close(Some(CLOSE_NO_ACCESS), Some("signed out"));
continue;
}
Err(e) => {
worker::console_error!("checking a feed: {}", e.0.message);
continue;
}
}
}
let mut ident = match crate::workspaces::feed_identity(&db, &user, &settings).await
{
Ok(i) => i,
Err(e) => {
worker::console_error!("feed identity: {}", e.0.message);
continue;
}
};
let messages = self.view_changed(&ident).await;
ident.token_id = token_id;
ident.checked_at = old.and_then(|o| o.checked_at);
let _ = ws.serialize_attachment(&ident);
for text in &messages {
Expand Down
Loading
Loading