From 281b5f7480d323bb8ce2337dec6dccd59f839aaa Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 09:15:10 -0400 Subject: [PATCH 1/2] Sign-in: one second factor per member; approval links check the team; narrower log reader role - Every sign-in path (Google, GitHub, password) asks for the member's one second factor: the authenticator-app code after a password too, and a member whose factor is the password account's code is sent to the password sign-in after Google or GitHub. Neither kind can be set up while the record has one; turning the password account's code off needs a session that passed it. - Plugin approval email links check, at approval time, that the approver is still on the team and their role holds plugins.approve. Removing a member takes them off every plugin's approver list. - The log reader role drops lambda:GetFunction, GetFunctionConfiguration and ListFunctions (function tags instead), uses ListStackResources for the stack lookup, and scopes DescribeStacks to CoderHelm's own update stacks. Comments state what the ECS task definition read returns. - With two-factor sign-in required, Settings, Sign-in and the API keys page mark live keys made before the rule, with whether their maker has a second factor now. --- docs/self-host/sign-in.md | 10 +- infra/cfn/coderhelm-log-reader-update.yaml | 18 +- infra/cfn/coderhelm-log-reader.yaml | 27 +- services/common/src/live/permissions.rs | 24 +- services/common/src/log_reader.rs | 44 +- services/common/src/log_repo.rs | 14 +- services/common/src/log_repo/live.rs | 268 ++++++------ services/common/src/log_repo/tests.rs | 53 ++- .../common/src/log_repo/tests/eval_cases.json | 4 +- services/common/src/plugins/install.rs | 79 ++++ services/gateway/src/routes/api_keys.rs | 24 +- services/gateway/src/routes/auth.rs | 22 + services/gateway/src/routes/plugin_pkgs.rs | 152 ++++++- services/gateway/src/routes/sign_in.rs | 398 ++++++++++++++++-- services/gateway/src/routes/users.rs | 30 +- 15 files changed, 949 insertions(+), 218 deletions(-) diff --git a/docs/self-host/sign-in.md b/docs/self-host/sign-in.md index 075b71d36..c81e80e10 100644 --- a/docs/self-host/sign-in.md +++ b/docs/self-host/sign-in.md @@ -40,7 +40,15 @@ With it on: - **People who sign in with a password** use Cognito's own two-factor codes: Cognito asks for the code at every sign-in. - **People who sign in with Google or GitHub** don't pass through Cognito's two-factor step, so CoderHelm asks for its own authenticator-app code right after Google or GitHub. Their secret is sealed with the install's KMS key. No sign-in path skips the code. - **Sessions from before the switch** are checked at their next request: someone already signed in without a code is sent to the setup screen, or asked to sign in again with their code. -- **API keys** are not people and keep working. **Settings, Sign-in** lists them, so you can revoke any you don't want. +- **API keys** are not people and keep working: a key never signs in, so the rule doesn't hold it back. **Settings, Sign-in** and **Settings, API keys** mark each live key made before the rule was turned on, with whether the person who made it has a second factor now (or has left the team). Such a key may have been made from a session without a second factor: check them and revoke any you don't recognize in **Settings, API keys**. Keys made after the rule is on come from sessions that passed it. + +### One second factor per person + +Email and password, Google and GitHub all lead to the same person in CoderHelm (by email), so each person has **one** second factor, and it is asked for however they sign in, whether the rule is on or not: + +- **An authenticator app set up in CoderHelm** (after Google or GitHub): its code is asked for after Google, GitHub and a password alike. +- **Cognito's code on the password account**: only Cognito can check it, so it is asked for at the password sign-in. Signing in with Google or GitHub sends the person back to sign in with their email and password. +- **Neither kind can be set up while the person has one**, from any session, including one held at the setup screen. To change it, turn the current one off first: the app code takes a current code to turn off, and the password account's code can be turned off only from a session that passed it. If someone lost their phone, an admin resets it (below). **Settings, Sign-in** shows who has set it up. If someone loses their phone, an admin can reset their two-factor sign-in after checking it's really them (a video call, say). The admin writes how they checked; the reset and the reason go in the log under **Settings, Roles**. The person sets it up again at their next sign-in. Only an owner can reset an admin's or another owner's. Nobody can reset their own. diff --git a/infra/cfn/coderhelm-log-reader-update.yaml b/infra/cfn/coderhelm-log-reader-update.yaml index d4b998452..c175691ed 100644 --- a/infra/cfn/coderhelm-log-reader-update.yaml +++ b/infra/cfn/coderhelm-log-reader-update.yaml @@ -3,6 +3,8 @@ Description: > Brings the existing CoderHelmLogReader role up to date with the read-only permissions the current CoderHelm release uses. Every permission here is read-only: CoderHelm can list, describe and query, never change anything. + It only adds: to drop a permission an older release granted, update the + CoderHelmLogReader stack itself with the current role template. Created from the dashboard's Update link; you can delete older CoderHelmLogReaderUpdate stacks once this one is in place. @@ -42,6 +44,11 @@ Resources: Action: - "iam:SimulatePrincipalPolicy" Resource: !Sub "arn:aws:iam::${AWS::AccountId}:role/${RoleName}" + - Sid: CheckOwnUpdateStack + Effect: Allow + Action: + - "cloudformation:DescribeStacks" + Resource: !Sub "arn:aws:cloudformation:*:${AWS::AccountId}:stack/CoderHelmLogReaderUpdate-*/*" - Sid: ReadMetrics Effect: Allow Action: @@ -59,6 +66,10 @@ Resources: Action: - "airflow:InvokeRestApi" Resource: "arn:aws:airflow:*:*:role/*/Viewer" + # A task definition as ECS returns it includes its containers' + # environment variables; CoderHelm keeps only the log + # configuration, start command, image, labels, storage, cpu and + # memory from it, and never stores or shows the environment. - Sid: DescribeServicesAndTasks Effect: Allow Action: @@ -69,15 +80,14 @@ Resources: - "ecs:ListTasks" - "ecs:DescribeTasks" Resource: "*" + # Tags, a stack's resource list and image manifests only: no + # function configuration or code, no stack parameters. - Sid: FindTheCodeBehindALogGroup Effect: Allow Action: - - "lambda:GetFunction" - - "lambda:GetFunctionConfiguration" - - "lambda:ListFunctions" - "lambda:ListTags" - "logs:ListTagsForResource" - - "cloudformation:DescribeStacks" + - "cloudformation:ListStackResources" - "ecr:BatchGetImage" - "ecr:ListTagsForResource" Resource: "*" diff --git a/infra/cfn/coderhelm-log-reader.yaml b/infra/cfn/coderhelm-log-reader.yaml index 4844d42af..745e7e330 100644 --- a/infra/cfn/coderhelm-log-reader.yaml +++ b/infra/cfn/coderhelm-log-reader.yaml @@ -88,9 +88,20 @@ Resources: Action: - "iam:SimulatePrincipalPolicy" Resource: !Sub "arn:aws:iam::${AWS::AccountId}:role/CoderHelmLogReader" + # Whether the dashboard's Update link was used: the status of + # CoderHelm's own update stacks only, no other stack. + - Sid: CheckOwnUpdateStack + Effect: Allow + Action: + - "cloudformation:DescribeStacks" + Resource: !Sub "arn:aws:cloudformation:*:${AWS::AccountId}:stack/CoderHelmLogReaderUpdate-*/*" # Before a fix for a log error is written: which tasks of the # service behind a log group are running, since when, and how - # they start. Lists and describes only. + # they start. Lists and describes only. A task definition as + # ECS returns it includes its containers' environment + # variables; CoderHelm keeps only the log configuration, start + # command, image, labels, storage, cpu and memory from it, and + # never stores or shows the environment. - Sid: DescribeTasksBehindLogErrors Effect: Allow Action: @@ -127,24 +138,22 @@ Resources: Version: "2012-10-17" Statement: # Which service writes a log group, so a fix goes to the repo its - # code lives in: describes and tags only. No image layers, no - # function code, nothing is changed. + # code lives in: tags, a stack's resource list (names and types) + # and image manifests only. No function configuration (it holds + # environment variables), no function code, no stack + # parameters, no image layers; nothing is changed. - Sid: DescribeServicesBehindLogGroups Effect: Allow Action: - "ecs:ListClusters" - "ecs:ListServices" - "ecs:DescribeServices" - - "ecs:DescribeTaskDefinition" - - "lambda:GetFunction" - - "lambda:GetFunctionConfiguration" - - "lambda:ListFunctions" - "lambda:ListTags" - "logs:ListTagsForResource" - - "cloudformation:DescribeStacks" + - "cloudformation:ListStackResources" - "ecr:BatchGetImage" - "ecr:ListTagsForResource" - Resource: "*" + Resource: "*"" Outputs: RoleArn: diff --git a/services/common/src/live/permissions.rs b/services/common/src/live/permissions.rs index f95462f71..91f9067a0 100644 --- a/services/common/src/live/permissions.rs +++ b/services/common/src/live/permissions.rs @@ -315,6 +315,11 @@ pub fn simulated_resource(action: &str, role_arn: &str, region: &str, account: & format!("arn:aws:airflow:{region}:{account}:role/coderhelm-permission-check/Viewer") } "iam:SimulatePrincipalPolicy" => role_arn.to_string(), + // Allowed on CoderHelm's own update stacks only. + "cloudformation:DescribeStacks" => format!( + "arn:aws:cloudformation:{region}:{account}:stack/{}/coderhelm-permission-check", + log_reader::update_stack_name() + ), _ => "*".to_string(), } } @@ -423,9 +428,10 @@ async fn probes(s: &Session) -> Vec<(&'static str, Option)> { .await .map(|_| ()) .map_err(|e| refused(&e)); - let code = client!(aws_sdk_lambda, s, s.region.clone()) - .list_functions() - .max_items(1) + // The role's own stack: a refusal means the ability is missing. + let code = client!(aws_sdk_cloudformation, s, s.region.clone()) + .list_stack_resources() + .stack_name(log_reader::ROLE_STACK) .send() .await .map(|_| ()) @@ -607,7 +613,7 @@ mod tests { .missing .contains(&"iam:SimulatePrincipalPolicy".to_string())); assert!(c.missing.contains(&"ecs:DescribeTasks".to_string())); - assert!(c.missing.contains(&"lambda:GetFunction".to_string())); + assert!(c.missing.contains(&"lambda:ListTags".to_string())); assert!(!c.missing.iter().any(|m| m.starts_with("airflow:"))); assert_eq!(c.missing_abilities(), vec!["check", "ecs", "code"]); } @@ -704,5 +710,15 @@ mod tests { simulated_resource("ecs:ListTasks", &t.role_arn, "r", "a"), "*" ); + // The stack read is allowed on CoderHelm's update stacks only. + assert!(simulated_resource( + "cloudformation:DescribeStacks", + &t.role_arn, + "eu-west-1", + "111122223333" + ) + .starts_with( + "arn:aws:cloudformation:eu-west-1:111122223333:stack/CoderHelmLogReaderUpdate-" + )); } } diff --git a/services/common/src/log_reader.rs b/services/common/src/log_reader.rs index b44b61c26..fe51590b1 100644 --- a/services/common/src/log_reader.rs +++ b/services/common/src/log_reader.rs @@ -63,8 +63,8 @@ pub const ABILITIES: &[Ability] = &[ Ability { key: "check", name: "Checking its own permissions", - why: "Asks IAM which of these permissions the role has, so this page can say when an update is needed. It only looks at this one role.", - actions: &["iam:SimulatePrincipalPolicy"], + why: "Asks IAM which of these permissions the role has, and whether CoderHelm's own update stack finished, so this page can say when an update is needed. It only looks at this one role and CoderHelm's update stacks.", + actions: &["iam:SimulatePrincipalPolicy", "cloudformation:DescribeStacks"], }, Ability { key: "metrics", @@ -85,7 +85,7 @@ pub const ABILITIES: &[Ability] = &[ Ability { key: "ecs", name: "ECS services and tasks", - why: "Sees which tasks behind a failing log group are running, since when and how they start, as evidence before a fix.", + why: "Sees which tasks behind a failing log group are running, since when and how they start, as evidence before a fix. A task definition comes with its environment variables; CoderHelm keeps only the start command, image, log setting, storage, cpu and memory.", actions: &[ "ecs:ListClusters", "ecs:ListServices", @@ -98,14 +98,11 @@ pub const ABILITIES: &[Ability] = &[ Ability { key: "code", name: "Finding the code behind a log group", - why: "Reads function, image and stack tags to work out which repository a log group's code lives in, so a fix goes to the right repo.", + why: "Reads function, image and log group tags, the names in a stack's resource list and image manifests to work out which repository a log group's code lives in, so a fix goes to the right repo. Never a function's configuration or code, or a stack's parameters.", actions: &[ - "lambda:GetFunction", - "lambda:GetFunctionConfiguration", - "lambda:ListFunctions", "lambda:ListTags", "logs:ListTagsForResource", - "cloudformation:DescribeStacks", + "cloudformation:ListStackResources", "ecr:BatchGetImage", "ecr:ListTagsForResource", ], @@ -362,13 +359,40 @@ mod tests { "ecs:ListTasks", "ecs:DescribeTasks", "ecs:DescribeServices", - "lambda:GetFunction", + "lambda:ListTags", ] { assert!(all.iter().any(|x| x == a), "{a}"); } assert!(!all.iter().any(|x| x == "sts:AssumeRole")); } + /// Nothing that hands over a function's configuration (its environment + /// variables) or code, or a stack's parameters; the one stack read is + /// CoderHelm's own update stack. + #[test] + fn no_function_configuration_code_or_stack_parameters() { + for t in [ROLE_TEMPLATE, UPDATE_TEMPLATE] { + let all = template_actions(t); + for a in [ + "lambda:GetFunction", + "lambda:GetFunctionConfiguration", + "lambda:ListFunctions", + "lambda:ListVersionsByFunction", + "cloudformation:GetTemplate", + ] { + assert!(!all.iter().any(|x| x == a), "{a}"); + } + let at = t.find("\"cloudformation:DescribeStacks\"").unwrap(); + let resource = t[at..].lines().nth(1).unwrap(); + assert!( + resource.contains("stack/CoderHelmLogReaderUpdate-*/*"), + "{resource}" + ); + assert_eq!(t.matches("cloudformation:DescribeStacks").count(), 1); + } + assert!(update_stack_name().starts_with("CoderHelmLogReaderUpdate-")); + } + #[test] fn missing_actions_follow_the_abilities() { assert!(missing_actions(&[]).is_empty()); @@ -376,7 +400,7 @@ mod tests { assert_eq!(m[0], "cloudwatch:GetMetricData"); assert_eq!(m.len(), 8); assert!(m.contains(&"ecs:DescribeTasks")); - assert!(!m.contains(&"lambda:GetFunction")); + assert!(!m.contains(&"lambda:ListTags")); } #[test] diff --git a/services/common/src/log_repo.rs b/services/common/src/log_repo.rs index e279a2985..bf4f6ff3e 100644 --- a/services/common/src/log_repo.rs +++ b/services/common/src/log_repo.rs @@ -9,9 +9,10 @@ //! definition that write to the log group (found by the task's own log //! configuration, not by its name), their container images and image //! labels (`org.opencontainers.image.source`), the ECR image's manifest -//! annotations and repository tags, the Lambda function and its tags, the -//! CloudFormation stack behind them (tags and description), and the log -//! group's own tags. A value that points at one of the team's repos (a +//! annotations and repository tags, the Lambda function's tags (never +//! its configuration, which carries its environment, nor its code), the +//! CloudFormation stack behind them (its name, and the functions in its +//! resource list), and the log group's own tags. A value that points at one of the team's repos (a //! GitHub URL, `owner/name`, or a repo's exact name) is evidence. //! 3. The team's code: a code search for the identifiers AWS gave (the log //! group, service, task family, function, image repository and stack @@ -30,8 +31,8 @@ //! for another repo is low. //! //! A resolution is cached per log group ([`Cached`]) and used again until -//! the evidence it rested on changes (a new task definition revision, new -//! Lambda code, the team's repos), or a week passes. +//! the evidence it rested on changes (a new task definition revision, the +//! log group's tags, the team's repos), or a week passes. use std::collections::{BTreeMap, BTreeSet}; @@ -163,7 +164,8 @@ pub struct LambdaFact { /// Container image, for image functions. pub image: String, pub tags: BTreeMap, - /// Changes when new code is deployed. + /// Changes when new code is deployed. No longer read (it comes only + /// with the function's configuration); kept for cached resolutions. pub code_sha: String, pub description: String, } diff --git a/services/common/src/log_repo/live.rs b/services/common/src/log_repo/live.rs index 843a04331..1afbc802b 100644 --- a/services/common/src/log_repo/live.rs +++ b/services/common/src/log_repo/live.rs @@ -28,11 +28,12 @@ const AWS_BUDGET: Duration = Duration::from_secs(20); const MAX_CLUSTERS: usize = 20; const MAX_SERVICES: usize = 300; const MAX_TASK_DEFS: usize = 80; -/// Most Lambda pages (50 functions each) read when the log group isn't the -/// function's default one. -const MAX_LAMBDA_PAGES: usize = 10; /// CloudFormation's own tag on every resource a stack made. const STACK_TAG: &str = "aws:cloudformation:stack-name"; +/// Most pages of a stack's resource list read (100 resources each). +const MAX_STACK_PAGES: usize = 5; +/// Most functions from the log group's stack looked up. +const MAX_STACK_FUNCTIONS: usize = 10; /// A described ECS service: (cluster, service name, task definition ARN, /// service tags, named directly by the target). @@ -136,18 +137,23 @@ impl Live<'_> { } } + // Functions the log group's own stack made (one with its own log + // group setting has no `/aws/lambda/` name to go by). + let stack_functions = if in_time(left()) { + self.stack_functions(s, facts).await + } else { + Vec::new() + }; if in_time(left()) { self.ecs(s, target, facts, started).await; } if in_time(left()) { - self.lambda(s, target, facts).await; + self.lambda(s, target, &stack_functions, facts).await; } if in_time(left()) { self.images(s, facts).await; } - if in_time(left()) { - self.stacks(s, facts).await; - } + stacks(facts); } /// The ECS services whose task definitions log to the group (read from @@ -344,113 +350,83 @@ impl Live<'_> { } } - /// The Lambda function behind the log group: the function whose default - /// log group it is, one whose logging setting names it, or those named - /// directly. - async fn lambda(&self, s: &Session, target: &Target, facts: &mut AwsFacts) { + /// The Lambda functions behind the log group: the function whose default + /// log group it is, those the log group's stack made, and those named + /// directly. Only their tags are read (`lambda:ListTags`): a function's + /// configuration carries its environment variables and `GetFunction` a + /// link to its code, so neither is asked for. + async fn lambda( + &self, + s: &Session, + target: &Target, + from_stack: &[String], + facts: &mut AwsFacts, + ) { let lambda = client!(aws_sdk_lambda, s); - let mut names: Vec = target.functions.clone(); - let groups = target.log_groups(); - // `/aws/lambda/` is the log group AWS gives every function. - for g in &groups { - if let Some(n) = g.strip_prefix("/aws/lambda/") { - if !n.is_empty() && !n.contains('/') && !names.iter().any(|x| x == n) { - names.push(n.to_string()); - } - } - } - let mut found = false; - for name in &names { - match lambda.get_function().function_name(name).send().await { - Ok(o) => { - let cfg = o.configuration(); - facts.lambdas.push(LambdaFact { - name: name.clone(), - image: o - .code() - .and_then(|c| c.image_uri()) - .unwrap_or_default() - .to_string(), - tags: o + let names = function_names(target, from_stack); + for name in names { + let mut fact = LambdaFact { + name: name.clone(), + ..Default::default() + }; + if let Some(arn) = function_arn(&s.region, &target.account, &name) { + match lambda.list_tags().resource(arn).send().await { + Ok(o) => { + fact.tags = o .tags() .map(|t| t.iter().map(|(k, v)| (k.clone(), v.clone())).collect()) - .unwrap_or_default(), - code_sha: cfg - .and_then(|c| c.code_sha256()) .unwrap_or_default() - .to_string(), - description: cfg - .and_then(|c| c.description()) - .unwrap_or_default() - .to_string(), - }); - found = true; + } + Err(e) if refused(&e) => facts.deny("lambda:ListTags"), + // No such function (a log group outliving it): nothing to say. + Err(e) if e.code() == Some("ResourceNotFoundException") => continue, + Err(_) => {} } - Err(e) if refused(&e) => facts.deny("lambda:GetFunction"), - Err(_) => {} } + facts.lambdas.push(fact); } - if found || groups.iter().all(|g| g.starts_with("/aws/lambda/")) { - return; - } - // A function with its own log group setting. - let mut marker: Option = None; - for _ in 0..MAX_LAMBDA_PAGES { - match lambda - .list_functions() - .set_marker(marker.take()) + } + + /// The Lambda functions the log group's CloudFormation stack made (the + /// stack-name tag CloudFormation puts on the group), read from the + /// stack's resource list: names and types only, never its parameters or + /// outputs. + async fn stack_functions(&self, s: &Session, facts: &mut AwsFacts) -> Vec { + let Some(stack) = facts.log_group_tags.get(STACK_TAG).cloned() else { + return Vec::new(); + }; + let cfn = client!(aws_sdk_cloudformation, s); + let mut resources: Vec<(String, String)> = Vec::new(); + let mut next: Option = None; + for _ in 0..MAX_STACK_PAGES { + match cfn + .list_stack_resources() + .stack_name(&stack) + .set_next_token(next.take()) .send() .await { Ok(o) => { - for f in o.functions() { - let logs_here = f - .logging_config() - .and_then(|l| l.log_group()) - .is_some_and(|g| groups.iter().any(|x| x == g)); - if logs_here { - let name = f.function_name().unwrap_or_default().to_string(); - let tags = match lambda - .list_tags() - .resource(f.function_arn().unwrap_or_default()) - .send() - .await - { - Ok(t) => t - .tags() - .map(|t| { - t.iter().map(|(k, v)| (k.clone(), v.clone())).collect() - }) - .unwrap_or_default(), - Err(e) => { - if refused(&e) { - facts.deny("lambda:ListTags"); - } - BTreeMap::new() - } - }; - facts.lambdas.push(LambdaFact { - name, - tags, - code_sha: f.code_sha256().unwrap_or_default().to_string(), - description: f.description().unwrap_or_default().to_string(), - ..Default::default() - }); - } - } - marker = o.next_marker().map(str::to_string); + resources.extend(o.stack_resource_summaries().iter().map(|r| { + ( + r.resource_type().unwrap_or_default().to_string(), + r.physical_resource_id().unwrap_or_default().to_string(), + ) + })); + next = o.next_token().map(str::to_string); } Err(e) => { if refused(&e) { - facts.deny("lambda:ListFunctions"); + facts.deny("cloudformation:ListStackResources"); } break; } } - if marker.is_none() { + if next.is_none() { break; } } + stack_lambdas(&resources) } /// The ECR images the containers and functions run: the manifest's @@ -534,43 +510,68 @@ impl Live<'_> { facts.images.push(fact); } } +} - /// The CloudFormation stacks that made the resources (CloudFormation's - /// own stack-name tag on them). - async fn stacks(&self, s: &Session, facts: &mut AwsFacts) { - let mut names: Vec = facts - .ecs - .iter() - .map(|e| &e.tags) - .chain(facts.lambdas.iter().map(|l| &l.tags)) - .chain(std::iter::once(&facts.log_group_tags)) - .filter_map(|t| t.get(STACK_TAG).cloned()) - .collect(); - names.sort(); - names.dedup(); - if names.is_empty() { - return; +/// The CloudFormation stacks that made the resources (CloudFormation's own +/// stack-name tag on them). Only their names: a stack's description comes +/// with its parameters, which aren't read. The stack's own tags are on the +/// resources it made, which are already read. +fn stacks(facts: &mut AwsFacts) { + let mut names: Vec = facts + .ecs + .iter() + .map(|e| &e.tags) + .chain(facts.lambdas.iter().map(|l| &l.tags)) + .chain(std::iter::once(&facts.log_group_tags)) + .filter_map(|t| t.get(STACK_TAG).cloned()) + .collect(); + names.sort(); + names.dedup(); + for name in names.into_iter().take(4) { + facts.stacks.push(StackFact { + name, + ..Default::default() + }); + } +} + +/// Pure: the functions to look up: those named directly, the one whose +/// default log group (`/aws/lambda/`) each group is, then those +/// the group's stack made; once each. +pub fn function_names(target: &Target, from_stack: &[String]) -> Vec { + let mut names: Vec = Vec::new(); + let mut add = |n: &str| { + if !n.is_empty() && !n.contains('/') && !names.iter().any(|x| x == n) { + names.push(n.to_string()); } - let cfn = client!(aws_sdk_cloudformation, s); - for name in names.into_iter().take(4) { - match cfn.describe_stacks().stack_name(&name).send().await { - Ok(o) => { - if let Some(st) = o.stacks().first() { - facts.stacks.push(StackFact { - name: name.clone(), - description: st.description().unwrap_or_default().to_string(), - tags: tag_map(st.tags().iter().map(|t| (t.key(), t.value()))), - }); - } - } - Err(e) => { - if refused(&e) { - facts.deny("cloudformation:DescribeStacks"); - } - } - } + }; + for f in &target.functions { + add(f); + } + for g in target.log_groups() { + if let Some(n) = g.strip_prefix("/aws/lambda/") { + add(n); } } + for f in from_stack.iter().take(MAX_STACK_FUNCTIONS) { + add(f); + } + names +} + +/// Pure: a function's ARN, for its tags. `None` without the account. +pub fn function_arn(region: &str, account: &str, name: &str) -> Option { + (crate::log_reader::is_account(account) && !region.is_empty() && !name.is_empty()) + .then(|| format!("arn:aws:lambda:{region}:{account}:function:{name}")) +} + +/// Pure: the Lambda functions in a stack's resource list (type, physical id). +pub fn stack_lambdas(resources: &[(String, String)]) -> Vec { + resources + .iter() + .filter(|(t, id)| t == "AWS::Lambda::Function" && !id.is_empty()) + .map(|(_, id)| id.clone()) + .collect() } /// Pure: an image manifest's (or index's) annotations, and those of its @@ -631,21 +632,6 @@ impl Env for Live<'_> { } } } - if !anchor.lambdas.is_empty() { - let lambda = client!(aws_sdk_lambda, s); - for (name, sha) in &anchor.lambdas { - if let Ok(o) = lambda - .get_function_configuration() - .function_name(name) - .send() - .await - { - if o.code_sha256().is_some_and(|n| n != sha) { - return true; - } - } - } - } false } diff --git a/services/common/src/log_repo/tests.rs b/services/common/src/log_repo/tests.rs index 96f0a4058..bcd1db57f 100644 --- a/services/common/src/log_repo/tests.rs +++ b/services/common/src/log_repo/tests.rs @@ -470,15 +470,15 @@ async fn when_the_model_fails_nothing_is_chosen_for_sure_or_cached() { async fn refused_lookups_name_the_permission_that_would_help() { let facts = AwsFacts { connected: true, - denied: vec!["ecs:ListClusters".into(), "lambda:GetFunction".into()], + denied: vec!["ecs:ListClusters".into(), "lambda:ListTags".into()], ..Default::default() }; let env = Fake::new(facts, answer("acme/web", "low", "Only a description fits")); let inp = input("/ecs/prod-render-worker", &["acme/web", "acme/api"]); let r = resolve(&env, &inp, t(NOW)).await; - assert_eq!(r.permissions, ["ecs:ListClusters", "lambda:GetFunction"]); + assert_eq!(r.permissions, ["ecs:ListClusters", "lambda:ListTags"]); let p = env.prompts.lock().unwrap()[0].clone(); - assert!(p.contains("The read-only role was refused: ecs:ListClusters, lambda:GetFunction")); + assert!(p.contains("The read-only role was refused: ecs:ListClusters, lambda:ListTags")); } #[tokio::test] @@ -734,3 +734,50 @@ fn id_for_kind(prompt: &str, kind: &str) -> Option { } mod eval; + +#[test] +fn functions_come_from_names_default_log_groups_and_the_stack() { + use super::live::{function_arn, function_names, stack_lambdas}; + let target = Target { + account: "111122223333".into(), + log_group: "/aws/lambda/render".into(), + functions: vec!["thumbs".into()], + samples: vec![LogLine { + log_group: "/custom/billing".into(), + message: "x".into(), + }], + ..Default::default() + }; + let from_stack = stack_lambdas(&[ + ("AWS::Lambda::Function".into(), "billing-fn".into()), + ("AWS::Logs::LogGroup".into(), "/custom/billing".into()), + ("AWS::Lambda::Function".into(), "render".into()), + ]); + assert_eq!(from_stack, ["billing-fn", "render"]); + assert_eq!( + function_names(&target, &from_stack), + ["thumbs", "render", "billing-fn"] + ); + assert_eq!( + function_arn("eu-west-1", "111122223333", "render").as_deref(), + Some("arn:aws:lambda:eu-west-1:111122223333:function:render") + ); + assert_eq!(function_arn("eu-west-1", "", "render"), None); +} + +/// The lookups read tags, names and manifests: never a function's +/// configuration or code, nor a stack's parameters. +#[test] +fn the_lookups_never_read_function_configuration_or_stack_parameters() { + let live = include_str!("live.rs"); + for call in [ + ".get_function()", + ".get_function_configuration()", + ".list_functions()", + ".describe_stacks()", + ".get_template()", + ] { + assert!(!live.contains(call), "{call}"); + } + assert!(live.contains(".list_tags()") && live.contains(".list_stack_resources()")); +} diff --git a/services/common/src/log_repo/tests/eval_cases.json b/services/common/src/log_repo/tests/eval_cases.json index 8acb738f4..70a92d9b3 100644 --- a/services/common/src/log_repo/tests/eval_cases.json +++ b/services/common/src/log_repo/tests/eval_cases.json @@ -278,7 +278,7 @@ "connected": true, "denied": [ "ecs:ListClusters", - "lambda:GetFunction" + "lambda:ListTags" ] }, "expect": null, @@ -287,7 +287,7 @@ "decoy": "acme/otter", "permissions": [ "ecs:ListClusters", - "lambda:GetFunction" + "lambda:ListTags" ] }, { diff --git a/services/common/src/plugins/install.rs b/services/common/src/plugins/install.rs index 90e634460..22797b25d 100644 --- a/services/common/src/plugins/install.rs +++ b/services/common/src/plugins/install.rs @@ -922,6 +922,53 @@ pub async fn set_limit( Ok(p) } +/// Takes a person who left the team off every plugin's approvers, so a +/// link already in their mail can't be used and they get no new ones. The +/// number of approvals a draft needs stays; an admin picks a new approver +/// when too few are left. Returns the plugins changed. +pub async fn drop_approver( + kv: &dyn Kv, + team: &str, + email: &str, + by: &str, +) -> Result, Refusal> { + let gone = email.trim().to_ascii_lowercase(); + if gone.is_empty() { + return Ok(Vec::new()); + } + let mut changed = Vec::new(); + for listed in list(kv, team).await? { + if !listed.approvers.members.iter().any(|m| m == &gone) { + continue; + } + // Read again with its revision: a change meanwhile is kept. + let (mut p, rev) = get(kv, team, &listed.id).await?; + p.approvers.members.retain(|m| m != &gone); + save(kv, team, &mut p, Some(rev)).await?; + let version = p + .current + .as_ref() + .map(|c| c.version.clone()) + .unwrap_or_default(); + audit::record( + kv, + team, + ev( + by, + ActorKind::Person, + action::PLUGIN_SETTINGS, + "ok", + &p, + &version, + ) + .detail(format!("approver {gone} removed: left the team")), + ) + .await; + changed.push(p.id); + } + Ok(changed) +} + /// Who approves the plugin's drafts (emails), and how many approvals each /// draft needs. pub async fn set_approvers( @@ -1216,6 +1263,38 @@ pub(crate) mod tests { assert_eq!(p.monthly_tokens, 2_000_000); } + #[tokio::test] + async fn a_person_who_leaves_the_team_is_taken_off_every_approver_list() { + let kv = Memory::new(); + let (_, src) = with_source(&kv).await; + install(&kv, TEAM, &src, "plugins/marketing", "admin@a.io", 1) + .await + .unwrap(); + set_approvers( + &kv, + TEAM, + "marketing", + vec!["left@a.io".into(), "stays@a.io".into()], + 1, + None, + "admin@a.io", + ) + .await + .unwrap(); + let changed = drop_approver(&kv, TEAM, " Left@A.io ", "admin@a.io") + .await + .unwrap(); + assert_eq!(changed, vec!["marketing".to_string()]); + let (p, _) = get(&kv, TEAM, "marketing").await.unwrap(); + assert_eq!(p.approvers.members, vec!["stays@a.io".to_string()]); + assert_eq!(p.approvers.min, 1); + // Someone on no list changes nothing. + assert!(drop_approver(&kv, TEAM, "nobody@a.io", "admin@a.io") + .await + .unwrap() + .is_empty()); + } + #[tokio::test] async fn a_lone_admin_installs_at_once_pinned_by_hash() { let kv = Memory::new(); diff --git a/services/gateway/src/routes/api_keys.rs b/services/gateway/src/routes/api_keys.rs index 97886e974..d2d7dc6d1 100644 --- a/services/gateway/src/routes/api_keys.rs +++ b/services/gateway/src/routes/api_keys.rs @@ -93,8 +93,30 @@ pub async fn list( }) }) .collect(); + // With two-factor sign-in required: the keys made before the rule, and + // whether their maker has a second factor now (a key never signs in). + let reviews = if super::sign_in::applies() { + super::sign_in::key_reviews(&state, &claims.team_id, &all) + .await + .unwrap_or_else(|e| { + error!("API key two-factor review not read: {e}"); + Default::default() + }) + } else { + Default::default() + }; + let views: Vec = all + .iter() + .map(|k| { + let mut v = key_view(k, now); + if let Some(r) = reviews.get(&k.id) { + v["two_factor_review"] = r.clone(); + } + v + }) + .collect(); Ok(Json(json!({ - "keys": all.iter().map(|k| key_view(k, now)).collect::>(), + "keys": views, "scopes": scopes, "limits": { "default_rate_per_minute": DEFAULT_RATE_PER_MINUTE, diff --git a/services/gateway/src/routes/auth.rs b/services/gateway/src/routes/auth.rs index a39e63d8b..e99bee498 100644 --- a/services/gateway/src/routes/auth.rs +++ b/services/gateway/src/routes/auth.rs @@ -1885,6 +1885,28 @@ async fn issue_session_from_cognito( }; let (team_id, user_id, role, github_login) = landing_parts(&record); touch_last_login(state, &team_id, &user_id).await; + // The member's second factor, whichever it is, comes before a session. + let step = SecondStep { + sub: user_id.clone(), + team_id: team_id.clone(), + email: email.to_string(), + role: role.clone(), + github_login: github_login.clone(), + via: "password".into(), + jti: String::new(), + aud: String::new(), + iat: 0, + exp: 0, + }; + if let Some(resp) = sign_in::password_step(state, step, proof.mfa) + .await + .map_err(|e| { + error!("Second factor not read: {e}"); + StatusCode::SERVICE_UNAVAILABLE + })? + { + return Ok(resp); + } return session_json( state, &team_id, diff --git a/services/gateway/src/routes/plugin_pkgs.rs b/services/gateway/src/routes/plugin_pkgs.rs index 4b2e6b589..2d1652514 100644 --- a/services/gateway/src/routes/plugin_pkgs.rs +++ b/services/gateway/src/routes/plugin_pkgs.rs @@ -1444,6 +1444,88 @@ pub struct EmailDecision { decision: String, } +type Item = std::collections::HashMap; + +/// The role of the team member with this email, if one is on the team now +/// (an invite doesn't count). +fn current_role(items: &[Item], email: &str) -> Option { + let get = |i: &Item, k: &str| { + i.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + items + .iter() + .find(|i| { + get(i, "email").trim().eq_ignore_ascii_case(email.trim()) + && get(i, "status") != "invited" + }) + .map(|i| match get(i, "role").as_str() { + "" => "member".to_string(), + r => r.to_string(), + }) +} + +/// The person an email link was sent to, as they are now: still on the team +/// and still allowed to approve plugin drafts. A link outlives neither. +async fn email_actor(state: &AppState, team: &str, email: &str) -> Result { + let gone = || "You aren't on this team any more, so this link no longer works.".to_string(); + let mut items = Vec::new(); + let mut start = None; + loop { + let out = state + .dynamo + .query() + .table_name(&state.config.users_table_name) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values( + ":pk", + aws_sdk_dynamodb::types::AttributeValue::S(team.into()), + ) + .expression_attribute_values( + ":p", + aws_sdk_dynamodb::types::AttributeValue::S("USER#".into()), + ) + .set_exclusive_start_key(start) + .send() + .await + .map_err(|e| { + warn!(error = %e, "Team not read for an email approval"); + "CoderHelm couldn't check this link just now. Try again.".to_string() + })?; + items.extend(out.items().iter().cloned()); + match out.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + let role = current_role(&items, email).ok_or_else(gone)?; + if !super::roles::holder_for_role(state, team, &role) + .await + .holds(CAP_APPROVE) + { + return Err("Your role can't approve plugin drafts any more.".into()); + } + Ok(drafts::Actor::new(email, false)) +} + +/// The capability behind every plugin draft decision. +const CAP_APPROVE: &str = "plugins.approve"; + +/// Takes a person who left the team off every plugin's approvers. Logged on +/// failure; the removal itself has happened (and an email link checks the +/// team anyway). +pub async fn member_removed(state: &AppState, team: &str, email: &str, by: &str) { + match install::drop_approver(&kv(state), team, email, by).await { + Ok(changed) if !changed.is_empty() => { + info!(team_id = %team, plugins = changed.len(), "Removed member taken off plugin approvers") + } + Ok(_) => {} + Err(r) => warn!(team_id = %team, error = %r.error, "Plugin approvers not updated"), + } +} + /// POST /plugins/approve (form: t, decision) — approves or rejects exactly /// the version the link names, as the approver it names. pub async fn email_approve( @@ -1461,8 +1543,17 @@ pub async fn email_approve( } }; let team = link.team_id.as_str(); + let who = match email_actor(&state, team, &link.email).await { + Ok(w) => w, + Err(e) => { + return ( + StatusCode::FORBIDDEN, + page("Can't use this link", &format!("

{}

", esc(&e))), + ) + .into_response() + } + }; let approvers = approvers_of(&kv, team, &a.plugin_id).await; - let who = drafts::Actor::new(&link.email, false); let result = if f.decision == "reject" { drafts::reject( &kv, @@ -1718,3 +1809,62 @@ pub async fn on_push(state: &AppState, team: &str, installation_id: u64, repo: & } } } + +#[cfg(test)] +mod tests { + use super::*; + use aws_sdk_dynamodb::types::AttributeValue; + + fn rec(email: &str, role: &str, status: &str) -> Item { + let mut i = Item::new(); + i.insert("email".into(), AttributeValue::S(email.into())); + if !role.is_empty() { + i.insert("role".into(), AttributeValue::S(role.into())); + } + if !status.is_empty() { + i.insert("status".into(), AttributeValue::S(status.into())); + } + i + } + + /// An email link counts only for someone on the team now: an invite or a + /// removed member is no one. + #[test] + fn an_email_approval_needs_someone_on_the_team_now() { + let items = vec![ + rec("admin@a.io", "admin", ""), + rec("plain@a.io", "", "active"), + rec("invited@a.io", "member", "invited"), + ]; + assert_eq!( + current_role(&items, "ADMIN@a.io ").as_deref(), + Some("admin") + ); + assert_eq!( + current_role(&items, "plain@a.io").as_deref(), + Some("member") + ); + assert_eq!(current_role(&items, "invited@a.io"), None); + assert_eq!(current_role(&items, "left@a.io"), None); + } + + /// The link checks the person and their role before anything changes, and + /// a removal takes them off the approver lists. + #[test] + fn the_email_link_checks_the_team_before_deciding() { + let me = include_str!("plugin_pkgs.rs"); + let start = me.find("pub async fn email_approve(").unwrap(); + let f = &me[start..start + me[start..].find("\n}\n").unwrap()]; + let check = f.find("email_actor(").unwrap(); + assert!(check < f.find("drafts::reject(").unwrap()); + assert!(check < f.find("drafts::approve(").unwrap()); + assert!(me.contains("holds(CAP_APPROVE)")); + assert!(crate::permissions::CAPABILITIES + .iter() + .any(|c| c.key == CAP_APPROVE && c.handlers.contains(&"plugin_pkgs::approve_draft"))); + let users = include_str!("users.rs"); + let start = users.find("pub async fn remove_user(").unwrap(); + let f = &users[start..start + users[start..].find("\n}\n").unwrap()]; + assert!(f.find(".delete_item()").unwrap() < f.find("plugin_pkgs::member_removed").unwrap()); + } +} diff --git a/services/gateway/src/routes/sign_in.rs b/services/gateway/src/routes/sign_in.rs index 469ce053e..215c91ca4 100644 --- a/services/gateway/src/routes/sign_in.rs +++ b/services/gateway/src/routes/sign_in.rs @@ -20,7 +20,12 @@ //! Two-factor: password accounts use Cognito's authenticator-app (TOTP) MFA. //! Google and GitHub sign-ins never pass through Cognito MFA, so CoderHelm //! asks for its own authenticator-app code after them (secret sealed with -//! the install's KMS key on the member record). The session token records +//! the install's KMS key on the member record). Every way in reaches the +//! same member record (by email), so a member has one second factor, and it +//! is asked for however they sign in: the app code after a password too, and +//! a member whose factor is the password account's code signs in with the +//! password (only Cognito can check that code). Neither kind can be set up +//! while the record has one ([`may_enroll`]). The session token records //! whether its sign-in passed a second factor ([`SignInProof`]); with the //! rule on, the auth middleware lets a session without one reach only the //! screens that set it up ([`gate`]). The rule is read on every request, so @@ -1028,16 +1033,8 @@ pub async fn app_setup( if !applies() { return Err(fail(StatusCode::NOT_FOUND, "Not available here.")); } - let item = member(&state, &claims.team_id, &claims.sub) - .await - .map_err(|e| internal("Member not read", e))? - .ok_or_else(|| fail(StatusCode::NOT_FOUND, "You aren't on this team."))?; - if app_enabled(&item) { - return Err(fail( - StatusCode::CONFLICT, - "Two-factor sign-in is already on for you.", - )); - } + // One second factor per member: none may be set up over another. + check_enroll(&state, &claims).await?; let mut secret = [0u8; 20]; rand::RngCore::fill_bytes(&mut rand::rng(), &mut secret); let sealed = seal(&state, &claims.team_id, &claims.sub, &secret) @@ -1089,6 +1086,8 @@ pub async fn app_verify( "Start the setup first: it shows the code to scan.", )); } + // A factor set up since the setup started (on the password account) wins. + check_enroll(&state, &claims).await?; let secret = unseal(&state, &claims.team_id, &claims.sub, pending) .await .map_err(|e| internal("Two-factor secret not read", e))?; @@ -1672,37 +1671,187 @@ pub async fn end_other_sessions( Ok(session_cookie(&token)) } -// ── Two-factor: the step after Google or GitHub ───────────────────── +// ── Two-factor: one second factor per member, on every way in ─────── + +/// The member's second factor, read to decide a sign-in or a setup: `app` +/// (CoderHelm's authenticator-app code) or `cognito` (the authenticator code +/// on their password account). Cognito is asked live, so a factor turned off +/// there doesn't linger. Unlike [`factor_of`], a read that fails is an error +/// (the caller refuses). +async fn enrolled_factor(state: &AppState, item: &Item) -> Result, String> { + if app_enabled(item) { + return Ok(Some("app".into())); + } + let email = s(item, "email"); + if email.is_empty() { + return Ok(None); + } + match state + .cognito + .admin_get_user() + .user_pool_id(&state.config.cognito_user_pool_id) + .username(email) + .send() + .await + { + Ok(u) => Ok(u + .user_mfa_setting_list + .is_some_and(|l| l.iter().any(|m| m == "SOFTWARE_TOKEN_MFA")) + .then(|| "cognito".to_string())), + Err(e) => { + let msg = format!("{e:?}"); + if msg.contains("UserNotFound") { + Ok(None) + } else { + Err(msg) + } + } + } +} + +/// What a sign-in still needs before it gets a session. +#[derive(Debug, PartialEq, Eq)] +pub enum StepNeeded { + /// Nothing more: no second factor, or it was just passed. + None, + /// CoderHelm's authenticator-app code. + AppCode, + /// The factor is the authenticator code on the password account, which + /// only Cognito can check: sign in with email and password. + UsePassword, +} -/// After a Google or GitHub sign-in: when the person has the -/// authenticator-app factor, the session waits for their code. Returns the -/// redirect to the code screen, or `None` to sign them straight in (no -/// factor yet: with the rule on, the session can then only set one up). +/// Whichever second factor the member has must be passed, however they +/// signed in. `passed` is a Cognito code on this very sign-in. +pub fn step_needed(factor: Option<&str>, passed: bool) -> StepNeeded { + match factor { + None => StepNeeded::None, + Some(_) if passed => StepNeeded::None, + Some("app") => StepNeeded::AppCode, + Some(_) => StepNeeded::UsePassword, + } +} + +/// What this sign-in still needs, read from the member's record. +async fn needed_for( + state: &AppState, + step: &SecondStep, + passed: bool, +) -> Result { + // A Cognito code on this sign-in is a factor the member has. + if passed { + return Ok(StepNeeded::None); + } + let Some(item) = member(state, &step.team_id, &step.sub).await? else { + return Ok(StepNeeded::None); + }; + Ok(step_needed( + enrolled_factor(state, &item).await?.as_deref(), + passed, + )) +} + +fn second_step_cookie(state: &AppState, step: &SecondStep) -> Result { + let token = jwt::create_second_step(step, &state.secrets.jwt_secret, SECOND_STEP_SECS) + .map_err(|e| e.to_string())?; + HeaderValue::from_str(&format!( + "{SECOND_STEP_COOKIE}={token}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age={SECOND_STEP_SECS}" + )) + .map_err(|e| e.to_string()) +} + +/// The error code for a federated or password sign-in whose factor is the +/// password account's code. +pub const USE_PASSWORD: &str = "two_factor_use_password"; + +/// After a Google or GitHub sign-in: the member's second factor, whichever +/// it is. Returns the redirect to the code screen (the authenticator-app +/// factor), back to sign-in with email and password (the password account's +/// factor), or `None` to sign them straight in (no factor yet: with the rule +/// on, the session can then only set one up). pub async fn second_step( state: &AppState, step: SecondStep, app_url: &str, ) -> Result, String> { - let Some(item) = member(state, &step.team_id, &step.sub).await? else { - return Ok(None); - }; - if !app_enabled(&item) { - return Ok(None); + match needed_for(state, &step, false).await? { + StepNeeded::None => Ok(None), + StepNeeded::UsePassword => Ok(Some( + ( + StatusCode::FOUND, + [(header::LOCATION, format!("{app_url}/?error={USE_PASSWORD}"))], + ) + .into_response(), + )), + StepNeeded::AppCode => { + let mut resp = ( + StatusCode::FOUND, + [(header::LOCATION, format!("{app_url}/?two_factor=1"))], + ) + .into_response(); + resp.headers_mut() + .append(header::SET_COOKIE, second_step_cookie(state, &step)?); + Ok(Some(resp)) + } } - let token = jwt::create_second_step(&step, &state.secrets.jwt_secret, SECOND_STEP_SECS) - .map_err(|e| e.to_string())?; - let mut resp = ( - StatusCode::FOUND, - [(header::LOCATION, format!("{app_url}/?two_factor=1"))], - ) - .into_response(); - let cookie = format!( - "{SECOND_STEP_COOKIE}={token}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age={SECOND_STEP_SECS}" - ); - if let Ok(v) = HeaderValue::from_str(&cookie) { - resp.headers_mut().append(header::SET_COOKIE, v); +} + +/// After an email and password sign-in: a member whose second factor is the +/// authenticator-app code enters it next (the same step as after Google or +/// GitHub). `passed` is whether Cognito asked for and took its own code. +/// Returns the answer to send instead of a session, or `None`. +pub async fn password_step( + state: &AppState, + step: SecondStep, + passed: bool, +) -> Result, String> { + match needed_for(state, &step, passed).await? { + StepNeeded::None => Ok(None), + StepNeeded::UsePassword => Ok(Some( + fail_code( + StatusCode::FORBIDDEN, + "Your two-factor code couldn't be checked. Sign in again.", + USE_PASSWORD, + ) + .into_response(), + )), + StepNeeded::AppCode => { + let mut resp = Json(json!({ "status": "second_step" })).into_response(); + resp.headers_mut() + .append(header::SET_COOKIE, second_step_cookie(state, &step)?); + Ok(Some(resp)) + } } - Ok(Some(resp)) +} + +/// May a member set up a second factor (either kind)? A member has one: while their record has one, neither kind can be set up (a +/// held session included); to change it, turn the one they have off first, +/// which takes its code. +pub fn may_enroll(existing: Option<&str>) -> Result<(), &'static str> { + match existing { + None => Ok(()), + Some("app") => Err( + "You already have two-factor sign-in with an authenticator app. Turn it off first (that takes a current code).", + ), + Some(_) => Err( + "You already have two-factor sign-in on your password account. Turn it off first.", + ), + } +} + +/// The setup check, read from the caller's own record. `Err` is the answer. +pub async fn check_enroll(state: &AppState, claims: &Claims) -> Result<(), ApiError> { + let Some(item) = member(state, &claims.team_id, &claims.sub) + .await + .map_err(|e| internal("Member not read", e))? + else { + return Err(fail(StatusCode::NOT_FOUND, "You aren't on this team.")); + }; + let factor = enrolled_factor(state, &item) + .await + .map_err(|e| internal("Two-factor sign-in not read", e))?; + may_enroll(factor.as_deref()) + .map_err(|m| fail_code(StatusCode::CONFLICT, m, "has_second_factor")) } fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { @@ -1921,9 +2070,34 @@ pub async fn get_settings( .unwrap_or_default() .iter() .filter(|k| k.is_live(now)) - .map(|k| json!({ "id": k.id, "name": k.name, "created_by": k.created_by_name })) + .map(|k| json!({ "id": k.id, "name": k.name, "created_by": k.created_by_name, "created_by_id": k.created_by, "created_at": k.created_at })) .collect() }; + // Keys made before the rule: whether their maker has a second factor now. + let require = org.as_ref().is_some_and(|o| o.require_2fa); + let since = org.as_ref().and_then(|o| o.require_2fa_since.clone()); + let keys: Vec = keys + .into_iter() + .map(|mut k| { + let before = made_before_rule( + k["created_at"].as_str().unwrap_or_default(), + require, + since.as_deref(), + ); + let maker = people + .iter() + .zip(active.iter()) + .find(|(_, i)| k["created_by_id"].as_str() == Some(s(i, "sk"))) + .map(|(p, _)| p["two_factor"].clone()); + k["made_before_rule"] = json!(before); + k["maker_on_team"] = json!(maker.is_some()); + k["maker_two_factor"] = maker.unwrap_or(Value::Null); + if let Some(o) = k.as_object_mut() { + o.remove("created_by_id"); + } + k + }) + .collect(); Ok(Json(json!({ "self_hosted": true, "is_org": org.as_ref().is_some_and(|o| o.team_id == claims.team_id), @@ -1937,6 +2111,69 @@ pub async fn get_settings( }))) } +/// Was this key made before two-factor sign-in was required? A key never +/// signs in, so the rule doesn't hold it back: one made before the rule may +/// have been made from a session without a second factor. Unknown (no time +/// for the rule, or a time that doesn't read) counts as before. +pub fn made_before_rule(created_at: &str, require_2fa: bool, since: Option<&str>) -> bool { + if !require_2fa { + return false; + } + let at = |v: &str| chrono::DateTime::parse_from_rfc3339(v).ok(); + match (at(created_at), since.and_then(at)) { + (Some(made), Some(rule)) => made < rule, + _ => true, + } +} + +/// For each live API key made before the rule was turned on: whether its +/// maker is still on the team and which second factor they have now. Keyed +/// by key id; keys that need no look are left out. +pub async fn key_reviews( + state: &AppState, + team_id: &str, + keys: &[crate::api_keys::StoredKey], +) -> Result, String> { + let now = chrono::Utc::now(); + let Some(org) = load_org(state).await? else { + return Ok(HashMap::new()); + }; + let flagged: Vec<&crate::api_keys::StoredKey> = keys + .iter() + .filter(|k| { + k.is_live(now) + && made_before_rule( + &k.created_at, + org.require_2fa, + org.require_2fa_since.as_deref(), + ) + }) + .collect(); + if flagged.is_empty() { + return Ok(HashMap::new()); + } + let members = team_members(state, team_id).await?; + let mut out = HashMap::new(); + for k in flagged { + let maker = members + .iter() + .find(|m| !is_invite(m) && s(m, "sk") == k.created_by); + let factor = match maker { + Some(m) => factor_of(state, m).await, + None => None, + }; + out.insert( + k.id.clone(), + json!({ + "made_before_rule": true, + "maker_on_team": maker.is_some(), + "maker_two_factor": factor, + }), + ); + } + Ok(out) +} + #[derive(Deserialize)] pub struct SettingsBody { pub domains: Option>, @@ -2737,6 +2974,97 @@ mod tests { .contains("cache")); } + /// Whichever second factor a member has is asked for after every way in. + #[test] + fn the_members_one_second_factor_is_asked_for_however_they_sign_in() { + // No factor: straight in (with the rule on, held until one is set up). + assert_eq!(step_needed(None, false), StepNeeded::None); + // The app code: after Google, GitHub and a password alike. + assert_eq!(step_needed(Some("app"), false), StepNeeded::AppCode); + // The password account's code: only Cognito checks it, so Google or + // GitHub goes back to the password sign-in. + assert_eq!(step_needed(Some("cognito"), false), StepNeeded::UsePassword); + // A Cognito code passed on this sign-in is the factor. + assert_eq!(step_needed(Some("cognito"), true), StepNeeded::None); + assert_eq!(step_needed(Some("app"), true), StepNeeded::None); + // Every path asks before it makes a session. + let auth = include_str!("auth.rs"); + let google = body(auth, "google_callback_inner"); + assert!(before( + google, + "sign_in::second_step", + "SignInProof::new(false, \"google\")" + )); + let github = body(auth, "github_callback_inner"); + assert!(before( + github, + "sign_in::second_step", + "SignInProof::new(false, \"github\")" + )); + let issue = body(auth, "issue_session_from_cognito"); + assert!(before(issue, "sign_in::password_step", "session_json(")); + assert!(issue.contains("proof.mfa")); + // The step reads the member's factor, either kind, and fails closed. + let me = include_str!("sign_in.rs"); + for f in ["second_step", "password_step"] { + assert!(body(me, f).contains("needed_for(state"), "{f}"); + } + let read = body(me, "enrolled_factor"); + assert!(read.contains("app_enabled(item)") && read.contains("SOFTWARE_TOKEN_MFA")); + assert!(read.contains("Err(msg)")); + } + + /// A member has one second factor: neither kind is set up over the other + /// or over itself, by a held session or any other. + #[test] + fn neither_factor_is_set_up_while_the_record_has_one() { + assert!(may_enroll(None).is_ok()); + assert!(may_enroll(Some("app")).is_err()); + assert!(may_enroll(Some("cognito")).is_err()); + let me = include_str!("sign_in.rs"); + let users = include_str!("users.rs"); + assert!(before(body(me, "app_setup"), "check_enroll", "seal(&state")); + assert!(before( + body(me, "app_verify"), + "check_enroll", + ".update_item()" + )); + assert!(before( + body(users, "mfa_setup"), + "sign_in::check_enroll", + ".associate_software_token()" + )); + assert!(before( + body(users, "mfa_verify_setup"), + "sign_in::check_enroll", + ".verify_software_token()" + )); + // Turning the password account's code off takes a session that passed it. + assert!(before( + body(users, "mfa_disable"), + "p.mfa", + ".admin_set_user_mfa_preference()" + )); + assert!(body(me, "check_enroll").contains("enrolled_factor")); + } + + /// With the rule on, keys made before it are flagged for a look. + #[test] + fn keys_made_before_the_rule_are_flagged() { + let since = Some("2026-10-20T12:00:00.000+00:00"); + assert!(!made_before_rule("2026-10-01T00:00:00Z", false, since)); + assert!(made_before_rule("2026-10-01T00:00:00Z", true, since)); + assert!(!made_before_rule("2026-10-21T00:00:00Z", true, since)); + // No time for the rule, or a key time that doesn't read: flagged. + assert!(made_before_rule("2026-10-21T00:00:00Z", true, None)); + assert!(made_before_rule("yesterday", true, since)); + // Both the API keys page and Settings, Sign-in show it. + let keys = include_str!("api_keys.rs"); + assert!(body(keys, "list").contains("sign_in::key_reviews")); + let settings = body(include_str!("sign_in.rs"), "get_settings"); + assert!(settings.contains("made_before_rule") && settings.contains("maker_two_factor")); + } + #[test] fn email_domains() { assert_eq!(email_domain("a@B.io").as_deref(), Some("b.io")); diff --git a/services/gateway/src/routes/users.rs b/services/gateway/src/routes/users.rs index 451e9b7fe..002d343c0 100644 --- a/services/gateway/src/routes/users.rs +++ b/services/gateway/src/routes/users.rs @@ -951,6 +951,16 @@ pub async fn remove_user( info!(user_id = %sk, team_id = %claims.team_id, "User removed"); + // Off every plugin's approvers, unless another record of theirs stays. + let email = s(target, "email"); + if !email.is_empty() + && !items + .iter() + .any(|i| s(i, "sk") != sk && s(i, "email").eq_ignore_ascii_case(email)) + { + super::plugin_pkgs::member_removed(&state, &claims.team_id, email, &claims.email).await; + } + Ok(Json(json!({ "status": "removed" }))) } @@ -1108,6 +1118,13 @@ pub async fn mfa_setup( Extension(claims): Extension, Json(body): Json, ) -> Result, StatusCode> { + // A self-hosted install: one second factor per member, so none is set + // up over the authenticator-app code. + if crate::routes::sign_in::applies() { + crate::routes::sign_in::check_enroll(&state, &claims) + .await + .map_err(|(code, _)| code)?; + } // Authenticate to get a Cognito access token let hash = cognito_secret_hash( &state.cognito_client_secret, @@ -1177,6 +1194,13 @@ pub async fn mfa_verify_setup( Extension(claims): Extension, Json(body): Json, ) -> Result { + // A self-hosted install: one second factor per member, so none is set + // up over the authenticator-app code. + if crate::routes::sign_in::applies() { + crate::routes::sign_in::check_enroll(&state, &claims) + .await + .map_err(|(code, _)| code)?; + } // Authenticate to get a Cognito access token let hash = cognito_secret_hash( &state.cognito_client_secret, @@ -1281,7 +1305,11 @@ pub async fn mfa_disable( if role_level(&claims.role) < 3 && claims.email.is_empty() { return Err(StatusCode::FORBIDDEN); } - // A self-hosted install that requires two-factor sign-in keeps it on. + // A self-hosted install: only a session that passed this code turns it + // off, and an install that requires two-factor sign-in keeps it on. + if crate::routes::sign_in::applies() && !proof.as_ref().is_some_and(|p| p.mfa) { + return Err(StatusCode::FORBIDDEN); + } if crate::routes::sign_in::applies() && crate::routes::sign_in::load_org(&state) .await From 8cddc44a8d3e5c44826b5882094867567ce656ee Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 09:52:29 -0400 Subject: [PATCH 2/2] Log reader template: fix a stray quote that broke the YAML --- infra/cfn/coderhelm-log-reader.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/infra/cfn/coderhelm-log-reader.yaml b/infra/cfn/coderhelm-log-reader.yaml index 745e7e330..0609263bf 100644 --- a/infra/cfn/coderhelm-log-reader.yaml +++ b/infra/cfn/coderhelm-log-reader.yaml @@ -153,7 +153,7 @@ Resources: - "cloudformation:ListStackResources" - "ecr:BatchGetImage" - "ecr:ListTagsForResource" - Resource: "*"" + Resource: "*" Outputs: RoleArn: