Merge NEXT: planning, generation map and portable configuration on top of the OIDC access model

NEXT predates the access work, so the identity layer follows master: access comes from
configured groups, instance administrators replace the site administration, and accounts are
created by SSO or by an administrator. Kept from NEXT: manual publication with the Review
changes panel and shared generator drafts, portable import/export (meguri/v2), the layered
generation map with binding provenance, JSM provider changes, contact/approval semantics and
the account-owned Person. Dropped: site administration, local sign-up, and the mandatory
unique email with its contact/account migrations. The manual-publication migration is
renumbered m_0010 after m_0009_access.

Accounts without an email still get a Person in every workspace they reach, a changed sign-in
email updates the account's person, and an account that loses access keeps its linked person so
schedules stay valid. Instance administrators may use Sync and shared drafts.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Aleksandr BogomiakovandClaude committed 2026-10-07 16:06:10 +01:00
commit 38105c65c2
57 files changed
+6890 -431

No files matched your search

+20 -6
View File
@@ -15,12 +15,26 @@ const baseUrl = () => process.env.MEGURI_BROWSER_URL || 'http://127.0.0.1:3000';
exports.baseUrl = baseUrl;
// The demo generates one password per server start and publishes it to the login screen.
// Generator drafts are shared and persisted per workspace, so a suite that edited a demo
// workspace without applying leaves them behind; discard them when a suite starts.
let password;
exports.demoPassword = () => password ||= fetch(baseUrl() + '/api/session').then(r => r.json()).then(session => {
exports.demoPassword = () => password ||= fetch(baseUrl() + '/api/session').then(r => r.json()).then(async session => {
if (!session.demo_lifecycle?.password) throw new Error('Browser tests require a disposable demo instance');
await discardDemoDrafts(session.demo_lifecycle.password);
return session.demo_lifecycle.password;
});
async function discardDemoDrafts(secret) {
const lead = await exports.apiLogin('alice', secret);
for (const { id } of (await lead.get('/api/workspaces')).workspaces) {
const detail = await lead.get('/api/workspaces/' + id);
const draft = detail.generation_draft;
if (!draft?.payload) continue;
const saved = detail.workspace.document.generation || {};
await lead.put(`/api/workspaces/${id}/generation-draft`, { revision: draft.revision, payload: { revision: detail.workspace.revision, variables: saved.variables || [], rules: saved.rules || [], route_position: saved.route_position || 0 } });
}
}
exports.signIn = async (page, username, secret) => {
await page.goto(baseUrl());
await page.getByLabel('Username', { exact: true }).fill(username);
@@ -54,21 +68,21 @@ exports.adminApi = () => exports.apiLogin('admin');
// Mutating suites each own one empty sandbox workspace ("Sandbox N", demo started with
// MEGURI_DEMO_SANDBOXES) whose groups are sandbox-N-leads (administrators) and sandbox-N-staff (employees).
// Nobody is in a sandbox except accounts created here, so suites do not depend on each other or on order.
exports.createUser = async (admin, { sandbox, role = 'admin', prefix, display }) => {
exports.createUser = async (admin, { sandbox, role = 'admin', prefix, display, email }) => {
const overview = await admin.get('/api/admin/overview');
const target = overview.workspaces.find(w => w.name === `Sandbox ${sandbox}` && !w.disabled_at);
if (!target) throw new Error(`Start the demo with MEGURI_DEMO_SANDBOXES>=${sandbox}: Sandbox ${sandbox} not found`);
const groups = role === 'admin' ? target.admin_groups : target.member_groups;
const username = `${prefix}-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`.toLowerCase();
const secret = 'local-browser-test-password';
await admin.post('/api/admin/users', { username, display_name: display, password: secret, groups });
return { username, password: secret, display, workspace: target };
await admin.post('/api/admin/users', { username, display_name: display, password: secret, groups, ...(email ? { email } : {}) });
return { username, password: secret, display, email, workspace: target };
};
// An administrator of exactly one sandbox, plus any employees (display names) created beside them.
exports.isolatedUser = async ({ sandbox, prefix, display, employees = [] }) => {
exports.isolatedUser = async ({ sandbox, prefix, display, email, employees = [] }) => {
const admin = await exports.adminApi();
const user = await exports.createUser(admin, { sandbox, role: 'admin', prefix, display });
const user = await exports.createUser(admin, { sandbox, role: 'admin', prefix, display, email });
const staff = [];
for (const name of employees) staff.push(await exports.createUser(admin, { sandbox, role: 'member', prefix: name.split(' ')[0], display: name }));
return { admin, ...user, staff };
+180 -20
View File
@@ -13,10 +13,17 @@ use tokio::{
pub struct State {
pub objects: BTreeMap<String, Value>,
pub writes: usize,
pub rotation_creates: usize,
pub rotation_patches: usize,
pub fail_after_rotation_patch: bool,
pub fail_after_schedule_patch: bool,
pub fail_once: Option<String>,
pub external_override: bool,
pub users: Vec<Value>,
pub lookups: usize,
pub fail_after_override_create: bool,
pub fail_after_resource_create: bool,
pub override_not_before: Option<chrono::DateTime<chrono::Utc>>,
}
pub struct Server {
pub base: String,
@@ -72,13 +79,14 @@ impl Server {
assert!(head.to_lowercase().contains("authorization: basic "));
let mut first = head.lines().next().unwrap().split_whitespace();
let method = first.next().unwrap();
let path = first.next().unwrap().split('?').next().unwrap();
let uri = first.next().unwrap();
let body = if length > 0 {
serde_json::from_slice(&buffer[head_end..head_end + length]).unwrap()
} else {
Value::Null
};
let (code, result) = handle(&mut shared.lock().unwrap(), method, path, body);
let (code, result) =
handle_page(&mut shared.lock().unwrap(), method, uri, body);
let body = result.to_string();
let response = format!(
"HTTP/1.1 {code} Result\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
@@ -91,6 +99,42 @@ impl Server {
Self { base, state, task }
}
}
fn handle_page(s: &mut State, method: &str, uri: &str, body: Value) -> (u16, Value) {
let url = reqwest::Url::parse(&format!("http://localhost{uri}")).unwrap();
let query: BTreeMap<_, _> = url.query_pairs().into_owned().collect();
let size = query.get("size").and_then(|s| s.parse::<usize>().ok());
if size.is_some_and(|size| size > 50) {
return (
422,
json!({"errors":[{"title":"Field: size, error: must be less than or equal to 50"}]}),
);
}
let (code, mut result) = handle(s, method, url.path(), body);
if method == "GET"
&& let Some(size) = size
&& let Some(values) = result.get_mut("values").and_then(Value::as_array_mut)
{
let offset = query
.get("offset")
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let more = offset + size < values.len();
*values = values.iter().skip(offset).take(size).cloned().collect();
if more {
result["links"] =
json!({"next":format!("{}?offset={}&size={size}",url.path(),offset+size)});
}
}
(code, result)
}
fn read_response(path: &str, value: &Value) -> Value {
let mut response = value.clone();
if path.contains("/escalations/") && response["repeat"]["waitInterval"] == 0 {
response.as_object_mut().unwrap().remove("repeat");
}
response
}
fn handle(s: &mut State, method: &str, path: &str, mut body: Value) -> (u16, Value) {
if method == "POST" && s.fail_once.as_ref().is_some_and(|p| path.ends_with(p)) {
s.fail_once = None;
@@ -102,19 +146,36 @@ fn handle(s: &mut State, method: &str, path: &str, mut body: Value) -> (u16, Val
return (200, json!(s.users));
}
if path.ends_with("/overrides") {
return (
200,
json!({"values":if s.external_override{vec![json!({"alias":"external"})]}else{vec![]}}),
);
if !s
.objects
.contains_key(path.strip_suffix("/overrides").unwrap())
{
return (404, json!({}));
}
let mut values: Vec<_> = s
.objects
.iter()
.filter(|(key, _)| {
key.rsplit_once('/')
.is_some_and(|(parent, _)| parent == path)
})
.map(|(_, value)| value.clone())
.collect();
if s.external_override {
values.push(json!({"alias":"external"}));
}
return (200, json!({"values":values}));
}
if let Some(parent) = path.strip_suffix("/rotations") {
return (
200,
json!({"values":s.objects.get(parent).unwrap()["rotations"]}),
);
let Some(object) = s.objects.get(parent) else {
return (404, json!({}));
};
let mut rotations = object["rotations"].as_array().unwrap().clone();
rotations.reverse();
return (200, json!({"values":rotations}));
}
if let Some(value) = s.objects.get(path) {
return (200, value.clone());
return (200, read_response(path, value));
}
if path.ends_with("/schedules")
|| path.ends_with("/escalations")
@@ -122,7 +183,7 @@ fn handle(s: &mut State, method: &str, path: &str, mut body: Value) -> (u16, Val
{
return (
200,
json!({"values":s.objects.iter().filter(|(k,_)|k.rsplit_once('/').is_some_and(|(p,_)|p==path)).map(|(_,v)|v.clone()).collect::<Vec<_>>()}),
json!({"values":s.objects.iter().filter(|(k,_)|k.rsplit_once('/').is_some_and(|(p,_)|p==path)).map(|(k,v)|read_response(k,v)).collect::<Vec<_>>()}),
);
}
return (404, json!({}));
@@ -133,6 +194,8 @@ fn handle(s: &mut State, method: &str, path: &str, mut body: Value) -> (u16, Val
s.external_override = false;
} else {
s.objects.remove(path);
s.objects
.retain(|key, _| !key.starts_with(&format!("{path}/")));
}
return (200, json!({"result":"deleted"}));
}
@@ -144,26 +207,123 @@ fn handle(s: &mut State, method: &str, path: &str, mut body: Value) -> (u16, Val
assert!((1..=20).contains(&body["repeat"]["count"].as_u64().unwrap()));
assert!(body["rules"].is_array());
}
if path.contains("schedules") {
for rotation in body["rotations"].as_array().unwrap() {
assert_eq!(rotation["participants"].as_array().unwrap().len(), 1);
assert!(
rotation["endDate"].as_str().unwrap() > rotation["startDate"].as_str().unwrap()
if path.contains("/overrides") {
assert!(body["responder"]["type"] == "user" || body["responder"]["type"] == "noone");
for field in ["startDate", "endDate"] {
let time = body[field]
.as_str()
.unwrap()
.parse::<chrono::DateTime<chrono::Utc>>()
.unwrap();
body[field] =
json!(chrono::DateTime::from_timestamp_millis(time.timestamp_millis()).unwrap());
}
if method == "POST"
&& s.override_not_before.is_some_and(|now| {
body["startDate"]
.as_str()
.unwrap()
.parse::<chrono::DateTime<chrono::Utc>>()
.unwrap()
< now
})
{
return (
400,
json!({"error":"Start time cannot be earlier than the current time"}),
);
}
s.writes += 1;
if method == "POST" {
let alias = uuid::Uuid::new_v4().to_string();
body["alias"] = json!(alias);
s.objects.insert(format!("{path}/{alias}"), body.clone());
if s.fail_after_override_create {
s.fail_after_override_create = false;
return (500, json!({"error":"Lost response after create"}));
}
} else {
assert_eq!(method, "PUT");
body["alias"] = json!(path.rsplit('/').next().unwrap());
s.objects.insert(path.into(), body.clone());
}
return (201, body);
}
if let Some((parent, id)) = path.split_once("/rotations/") {
assert_eq!(method, "PATCH");
let Some(rotation) = s
.objects
.get_mut(parent)
.and_then(|v| v["rotations"].as_array_mut())
.and_then(|r| r.iter_mut().find(|r| r["id"] == id))
else {
return (404, json!({}));
};
body["id"] = json!(id);
*rotation = body.clone();
s.writes += 1;
s.rotation_patches += 1;
if s.fail_after_rotation_patch {
s.fail_after_rotation_patch = false;
return (500, json!({"error":"Lost rotation update response"}));
}
return (200, body);
}
if path.contains("schedules") && body.get("rotations").is_some() {
let zone = body["timezone"]
.as_str()
.unwrap()
.parse::<chrono_tz::Tz>()
.unwrap();
for rotation in body["rotations"].as_array_mut().unwrap() {
rotation["id"] = json!(uuid::Uuid::new_v4().to_string());
s.rotation_creates += 1;
assert!(!rotation["participants"].as_array().unwrap().is_empty());
if let Some(end) = rotation["endDate"].as_str() {
assert!(end > rotation["startDate"].as_str().unwrap());
} else {
assert_eq!(rotation["participants"][0]["type"], "noone");
}
// Anonymized live behavior: native rotation minutes snap to a half-hour;
// override endpoints above retain arbitrary minutes and milliseconds.
for field in ["startDate", "endDate"] {
if let Some(raw) = rotation[field].as_str() {
use chrono::Timelike;
let time = raw.parse::<chrono::DateTime<chrono::Utc>>().unwrap();
let minute = i64::from(time.with_timezone(&zone).minute());
let rounded =
time + chrono::Duration::minutes(((minute + 15) / 30) * 30 - minute);
rotation[field] = json!(
chrono::DateTime::from_timestamp_millis(rounded.timestamp_millis())
.unwrap()
);
}
}
}
}
s.writes += 1;
if method == "POST" {
let id = uuid::Uuid::new_v4().to_string();
body["id"] = json!(id);
s.objects.insert(format!("{path}/{id}"), body.clone());
if s.fail_after_resource_create {
s.fail_after_resource_create = false;
return (500, json!({"error":"Lost resource create response"}));
}
return (201, body);
}
assert_eq!(method, "PATCH");
if let Some(previous) = s.objects.get(path) {
body["id"] = previous["id"].clone();
s.objects.insert(path.into(), body.clone());
(200, body)
let mut merged = previous.clone();
for (key, value) in body.as_object().unwrap() {
merged[key] = value.clone();
}
s.objects.insert(path.into(), merged.clone());
if path.starts_with("/schedules/") && s.fail_after_schedule_patch {
s.fail_after_schedule_patch = false;
return (500, json!({"error":"Lost schedule metadata response"}));
}
(200, merged)
} else {
(404, json!({}))
}
+32 -2
View File
@@ -6,7 +6,7 @@ use meguri::{
admin::{self, NewUser},
domain::*,
identity,
models::UserRow,
models::{HistoryRow, UserRow},
service,
store::{Store, WorkspaceRecord},
};
@@ -59,7 +59,7 @@ pub async fn account(db: &Store, config: &Config, name: &str, groups: &[String])
username: format!("test-{}", Uuid::new_v4().simple()),
display_name: name.into(),
password: "test-only-password".into(),
email: None,
email: Some(format!("{}@example.com", Uuid::new_v4())),
groups: groups.to_vec(),
country: None,
},
@@ -123,6 +123,13 @@ impl Fixture {
config,
}
}
/// Makes `user` a workspace administrator of the fixture workspace through the group mapping.
pub async fn make_admin(&self, user: &User) {
let groups = self.config.workspaces[0].admin_groups.clone();
identity::apply_access(&self.db, &self.config, user.id, Some(groups))
.await
.unwrap();
}
/// A second workspace whose administrator group is granted to `admin` only.
pub async fn extra_workspace(&self, name: &str, admin: &User) -> WorkspaceRecord {
let extra = unique_workspace(name);
@@ -175,6 +182,29 @@ impl Fixture {
}
}
pub async fn prioritize_publication(&self) {
let revision = self.db.workspace(self.team.id).await.unwrap().revision;
self.db
.retry(self.team.id, self.people[0].id, revision)
.await
.unwrap();
// PostgreSQL and the worker can run on different host clocks. Publish only
// once this test's latest committed revision has actually become effective.
let workspace = self.team.id.to_string();
let effective = query!(HistoryRow, $workspace_id == workspace)
.all(&self.db.db)
.await
.unwrap()
.into_iter()
.map(|row| row.effective_at)
.max()
.unwrap();
if let Ok(delay) = (effective - Utc::now()).to_std() {
assert!(
delay < std::time::Duration::from_secs(2),
"Database clock is too far ahead of the test worker"
);
tokio::time::sleep(delay + std::time::Duration::from_millis(1)).await;
}
// The worker takes a bounded batch. Repeated runs leave other test tenants
// in this disposable database, so explicitly put this test's job first.
self.db