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
10 changes: 10 additions & 0 deletions crates/fctl-client/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2300,6 +2300,16 @@ impl Api {
.await
}

/// What saving `policy` in place of the instance's session policy
/// would end at once, before anything changes (admins). Saving it is
/// [`Self::update_instance_settings`] with its fields.
pub async fn session_policy_preview(
&self,
policy: &SessionPolicy,
) -> Result<SessionPolicyPreview> {
self.post("/admin/sign-in/sessions/preview", policy).await
}

/// Invites an address to the instance, and to workspaces you are an
/// admin of.
pub async fn invite(&self, req: &CreateInviteRequest) -> Result<Invite> {
Expand Down
32 changes: 32 additions & 0 deletions crates/fctl-control/src/api/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1162,6 +1162,33 @@ pub async fn update_settings(ctx: &mut Ctx, req: &mut Request) -> AppResult<Resp
if let Some(on) = body.self_sign_up {
settings.self_sign_up = on;
}
// Where people sign in from: never so that the admin who saves it is
// outside, unless they're the primary instance owner, who signs in
// from anywhere.
if let Some(networks) = &body.networks {
let networks = fctl_domain::networks::check(networks).map_err(crate::error::AppError)?;
if !fctl_domain::networks::admits(&networks, ctx.ip.as_deref())
&& actor.role() != InstanceRole::Owner
{
return Err(conflict(&format!(
"Your own address, {}, isn't in these networks: saving them would shut you out. Add it, or save them from inside one.",
ctx.ip.as_deref().unwrap_or("unknown")
)));
}
settings.networks = networks;
}
// How long sign-ins last: what it doesn't let last ends once it's
// saved.
let policy = verify::session_policy(&settings, &body);
let policy_changed = policy != settings.session_policy();
if policy_changed {
fctl_domain::session_policy::check(&policy).map_err(crate::error::AppError)?;
settings.browser_max_hours = policy.browser_max_hours;
settings.browser_idle_minutes = policy.browser_idle_minutes;
settings.cli_max_days = policy.cli_max_days;
settings.access_token_max_days = policy.access_token_max_days;
settings.member_access_tokens = policy.member_access_tokens;
}
// No admin signs themselves out who might not sign in again: they
// sign in with the provider first, which shows it works.
let mut change = None;
Expand All @@ -1182,6 +1209,11 @@ pub async fn update_settings(ctx: &mut Ctx, req: &mut Request) -> AppResult<Resp
.await?;
crate::api::sign_in::tell(ctx, change, &settings.sign_in);
}
if policy_changed {
crate::sign_in::revoke_ended(&ctx.db, &policy, ctx.now)?
.run()
.await?;
}
if gravatar_off {
// The copies go, and turned on again, it looks for everyone anew.
crate::db::batch(
Expand Down
34 changes: 33 additions & 1 deletion crates/fctl-control/src/api/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub async fn instance(ctx: &Ctx) -> AppResult<Response> {
admin_tokens: ctx.cfg.admin_tokens,
service_account_consent: settings.service_account_consent,
},
sign_in: Some(crate::sign_in::info(&ctx.cfg, &settings)),
sign_in: Some(crate::sign_in::info(&ctx.cfg, &settings, ctx.ip.as_deref())),
})
}

Expand Down Expand Up @@ -237,6 +237,12 @@ pub async fn signup(ctx: &mut Ctx, req: &mut Request) -> AppResult<Response> {
"An account with this email already exists. Sign in instead.",
));
}
// From outside the instance's networks, before the account and the
// invitation's use are written: nobody new signs in from there.
let networks = crate::instance::settings(&ctx.db).await?.networks;
if !fctl_domain::networks::admits(&networks, ctx.ip.as_deref()) {
return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref())));
}
// Where its domain signs in with a provider, the invitation is taken
// with that provider's sign-in, which makes the account (`api::sign_in`).
let settings = crate::instance::settings(&ctx.db).await?;
Expand Down Expand Up @@ -326,6 +332,11 @@ pub async fn login(ctx: &mut Ctx, req: &mut Request) -> AppResult<Response> {
if let Err(required) = user.admits(&instance, &SignedIn::password()) {
return Err(AppError(crate::sign_in::password_refused(&required)));
}
// Before a code is asked for: from outside the instance's networks it
// would sign nobody in.
if crate::sign_in::outside(&instance, ctx.ip.as_deref(), &user, true) {
return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref())));
}
let settings = user.two_factor_settings(&instance);
if two_factor::asks(
&settings,
Expand Down Expand Up @@ -749,6 +760,11 @@ pub async fn reset_password(ctx: &mut Ctx, req: &mut Request) -> AppResult<Respo
if let Some(required) = user.sign_in_required(&instance) {
return Err(AppError(crate::sign_in::password_refused(&required)));
}
// Nor one that would, from outside the instance's networks, sign out
// everywhere someone who can't sign in here.
if crate::sign_in::outside(&instance, ctx.ip.as_deref(), &user, true) {
return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref())));
}
validate::password(&body.new_password, Some(&user.email))?;
let phc = auth::hash_password(&body.new_password)?;
// With two-factor, the link alone changes nothing: the new password
Expand Down Expand Up @@ -942,6 +958,20 @@ pub async fn device_poll(ctx: &mut Ctx, req: &mut Request) -> AppResult<Response
&DevicePollResponse::Pending
});
}
// From outside the instance's networks, the approval waits for a poll
// from inside one (a VPN turned back on) rather than being used up.
if let Some(user_id) = row.user_id.as_deref()
&& row.token_id.is_none()
&& let Some(user) = auth::user_by_id(ctx, user_id).await?
&& crate::sign_in::outside(
&crate::instance::settings(&ctx.db).await?,
ctx.ip.as_deref(),
&user,
true,
)
{
return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref())));
}
// Approved: issue the CLI token exactly once.
let claimed = q(
&ctx.db,
Expand Down Expand Up @@ -980,13 +1010,15 @@ pub async fn device_poll(ctx: &mut Ctx, req: &mut Request) -> AppResult<Response
if !user.is_active() {
return http::ok(&DevicePollResponse::Denied);
}
let settings = crate::instance::settings(&ctx.db).await?;
let (_, token) = auth::issue_token(
ctx,
&user.id,
TokenKind::Cli,
auth::NewToken {
name: Some(&row.client_name),
how: SignedIn::read(row.auth_method.as_deref(), row.auth_domain.as_deref()),
settings: Some(&settings),
..auth::NewToken::default()
},
)
Expand Down
54 changes: 54 additions & 0 deletions crates/fctl-control/src/api/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ async fn login(
if let Err(required) = user.admits(&settings, &how) {
return wrong_account(p, &required);
}
if crate::sign_in::outside(&settings, ctx.ip.as_deref(), &user, true) {
return fail("/login", "network", "");
}
return sign_in(ctx, user, return_to, how, &settings).await;
}
if p.email.is_none() || !p.verified {
Expand Down Expand Up @@ -225,6 +228,9 @@ async fn login(
if !settings.self_sign_up && !AllowPattern::parse(&pattern).is_ok_and(|a| a.is_exact()) {
return fail("/login", "sign_up_closed", "");
}
if !fctl_domain::networks::admits(&settings.networks, ctx.ip.as_deref()) {
return fail("/login", "network", "");
}
sign_up(ctx, p, &email, role, return_to).await
}

Expand Down Expand Up @@ -447,6 +453,11 @@ async fn first_sign_in(
{
return wrong_account(p, &required);
}
// Linking nothing from outside the instance's networks, where it would
// sign nobody in.
if crate::sign_in::outside(settings, ctx.ip.as_deref(), &user, true) {
return fail("/login", "network", "");
}
// A rule makes the provider the way in for the address's domain: its
// domains, where it does. Not for the primary instance owner, whom the
// rules don't hold and who links it from Settings, as before them.
Expand Down Expand Up @@ -764,6 +775,7 @@ pub async fn overview(ctx: &Ctx) -> AppResult<Response> {
let people = crate::sign_in::people(&ctx.db).await?;
let how = signed_in_with(ctx);
let count = |f: fn(&rules::Person) -> bool| people.iter().filter(|p| f(p)).count() as u32;
let sessions = settings.session_policy();
http::ok(&SignInOverview {
providers: crate::sign_in::statuses(&ctx.cfg, &people),
coverage: settings
Expand All @@ -781,9 +793,51 @@ pub async fn overview(ctx: &Ctx) -> AppResult<Response> {
method: how.method_str().map(str::to_owned),
method_domain: how.domain,
email: ctx.cfg.email.is_some(),
sessions,
networks: settings.networks.clone(),
address: ctx.ip.clone(),
})
}

/// `POST /api/v1/admin/sign-in/sessions/preview`: what saving the
/// request's session policy would end at once, before anything changes.
pub async fn sessions_preview(ctx: &Ctx, req: &mut Request) -> AppResult<Response> {
let actor = ctx.admin()?.clone();
let policy: SessionPolicy = http::body(req).await?;
fctl_domain::session_policy::check(&policy).map_err(AppError)?;
let mut p = SessionPolicyPreview::default();
for (kind, member, n) in crate::sign_in::ended_by_policy(&ctx.db, &policy, ctx.now).await? {
match kind {
TokenKind::Web => p.browsers += n,
TokenKind::Cli => p.clis += n,
TokenKind::Pat => {
p.access_tokens += n;
if member {
p.member_tokens += n;
}
}
}
}
// The sign-in this request comes with, used just now: one of those, if
// it's too old. An admin token isn't one.
p.you = ctx.auth.as_ref().is_some_and(|a| {
!a.admin_token
&& fctl_domain::session_policy::ended(
&policy,
&fctl_domain::session_policy::Token {
kind: a.kind,
created_at: a.signed_in_at,
last_used_at: Some(ctx.now),
expires_at: None,
member: actor.role() == fctl_proto::session::InstanceRole::Member,
},
ctx.now,
)
.is_some()
});
http::ok(&p)
}

/// How the caller's sign-in was made.
fn signed_in_with(ctx: &Ctx) -> SignedIn {
ctx.auth
Expand Down
65 changes: 55 additions & 10 deletions crates/fctl-control/src/api/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ use crate::error::{AppError, AppResult, not_found, validation};
use crate::http;
use crate::model::PROJECT_VISIBLE;
use fctl_domain::limits::{Limits, MAX_PLACES, Places};
use fctl_domain::session_policy;
use fctl_domain::validate;
use fctl_domain::verify::Sensitive;
use fctl_proto::TokenId;
use fctl_proto::api::*;
use fctl_proto::{ApiError, TokenId};
use serde::Deserialize;
use std::collections::HashMap;
use worker::{Request, Response};
Expand Down Expand Up @@ -134,16 +135,35 @@ impl TokenRow {
Limits::parse(self.scope.as_deref())
}

fn info(self, current: &str, named: &Named) -> TokenInfo {
/// It as the instance's session policy reads it (`member`: its person
/// is a member of the instance, not an admin).
fn token(&self, member: bool) -> session_policy::Token {
session_policy::Token {
kind: TokenKind::parse(&self.kind).unwrap_or(TokenKind::Pat),
created_at: self.created_at,
last_used_at: self.last_used_at,
expires_at: self.expires_at,
member,
}
}

/// Whether `policy` still lets it sign its person in at `now`.
fn live(&self, policy: &SessionPolicy, member: bool, now: i64) -> bool {
session_policy::ended(policy, &self.token(member), now).is_none()
}

/// What people see of it, as `policy` lets it last.
fn info(self, current: &str, named: &Named, policy: &SessionPolicy) -> TokenInfo {
let scope = self.limits().map(|l| named.scope(&l));
let expires_at = session_policy::ends_at(policy, &self.token(false));
TokenInfo {
current: self.id == current,
id: TokenId(self.id),
kind: TokenKind::parse(&self.kind).unwrap_or(TokenKind::Pat),
name: self.name,
created_at: self.created_at,
last_used_at: self.last_used_at,
expires_at: self.expires_at,
expires_at,
user_agent: self.user_agent,
scope,
method: self.auth_method,
Expand All @@ -170,10 +190,20 @@ pub async fn list(ctx: &Ctx) -> AppResult<Response> {
)?
.all()
.await?;
// Those the instance's session policy ended are gone.
let policy = ctx.settings().session_policy();
let member = user.role() == fctl_proto::session::InstanceRole::Member;
let rows: Vec<TokenRow> = rows
.into_iter()
.filter(|r| r.live(&policy, member, ctx.now))
.collect();
let limits: Vec<Limits> = rows.iter().filter_map(TokenRow::limits).collect();
let named = Named::of(ctx, &user.id, &limits.iter().collect::<Vec<_>>()).await?;
http::ok(&TokenList {
tokens: rows.into_iter().map(|r| r.info(&current, &named)).collect(),
tokens: rows
.into_iter()
.map(|r| r.info(&current, &named, &policy))
.collect(),
})
}

Expand All @@ -195,7 +225,11 @@ pub async fn current(ctx: &Ctx) -> AppResult<Option<TokenInfo>> {
};
let limits = row.limits();
let named = Named::of(ctx, &a.user.id, &limits.iter().collect::<Vec<_>>()).await?;
Ok(Some(row.info(&a.token_id, &named)))
Ok(Some(row.info(
&a.token_id,
&named,
&a.settings.session_policy(),
)))
}

/// The places a new token names: workspaces the caller is a member of and
Expand Down Expand Up @@ -266,12 +300,21 @@ async fn places(
pub async fn create(ctx: &mut Ctx, req: &mut Request) -> AppResult<Response> {
let body: CreateTokenRequest = http::body(req).await?;
let user = ctx.user()?.clone();
let settings = ctx.settings();
let policy = settings.session_policy();
// Where members make none, they use the CLI signed in as themselves.
if !policy.member_access_tokens && user.role() == fctl_proto::session::InstanceRole::Member {
return Err(AppError(ApiError::forbidden(
"Only this instance's admins make access tokens: use the CLI signed in as you (fctl login), or ask an admin.",
)));
}
let name = validate::name("name", &body.name)?;
let expires_at = match body.expires_in_days {
Some(0) | None => None,
Some(d) if d <= 3650 => Some(ctx.now + d as i64 * DAY_MS),
Some(_) => return Err(validation("expires_in_days", "Use at most 3650 days")),
};
let days = body.expires_in_days.filter(|d| *d > 0);
if days.is_some_and(|d| d > fctl_proto::api::MAX_ACCESS_TOKEN_DAYS) {
return Err(validation("expires_in_days", "Use at most 3650 days"));
}
session_policy::check_token_days(&policy, days).map_err(AppError)?;
let expires_at = days.map(|d| ctx.now + i64::from(d) * DAY_MS);
let access = body.access.unwrap_or_default();
fctl_domain::limits::check(access, body.github_access).map_err(AppError)?;
let places = places(ctx, &body.workspaces, &body.projects).await?;
Expand All @@ -295,6 +338,7 @@ pub async fn create(ctx: &mut Ctx, req: &mut Request) -> AppResult<Response> {
limits: limits.as_ref(),
verified_at: None,
how,
settings: Some(&settings),
},
)
.await?;
Expand Down Expand Up @@ -375,5 +419,6 @@ pub fn limited_me(user: &crate::model::UserRow, token: Option<TokenInfo>) -> Me
claude_stand_in: false,
export: None,
sign_in: None,
sessions: None,
}
}
Loading
Loading