Skip to main content

tilo_action_policy/
acting.rs

1//! Who made a change: one tree, and the one admission every action API takes.
2
3use crate::{
4    Admission, Answer, Asker, Authority, Context, Grant, GrantId, Grantee, Invoked, Party, Reach,
5    Refused, TreePath, WorkspacePolicy, admit,
6};
7use tilo_member_types::{Actor, MemberId};
8
9/// [`ActingPolicy::asker`] for an acting with software or a device between
10/// the person and the change when `delegated`.
11#[must_use]
12pub const fn asker_of(delegated: bool, host_reaches_person: bool) -> Asker {
13    Asker {
14        reachable: !delegated || host_reaches_person,
15        delegated,
16    }
17}
18
19/// What the workspace's policy reads from who acted ([`tilo_member_types::Acting`]): who an invocation asks,
20/// and the grants a handed agent of its tree carries.
21pub trait ActingPolicy {
22    /// Who an invocation of this acting asks.
23    fn asker(&self, host_reaches_person: bool) -> Asker;
24    /// The preset every handed agent of the tree carries in `workspace`.
25    fn handed_preset(&self, workspace: &str) -> Vec<Grant>;
26}
27
28impl ActingPolicy for tilo_member_types::Acting {
29    /// Who an invocation of this acting asks: the person, who can answer when
30    /// they act themselves or when the host running it reaches them
31    /// (`host_reaches_person`); and whether someone acts for them, who is
32    /// asked before an action the person attends.
33    fn asker(&self, host_reaches_person: bool) -> Asker {
34        asker_of(self.delegated(), host_reaches_person)
35    }
36
37    /// The preset every handed agent of the tree carries in `workspace`
38    /// ([`tilo_member_types::Acting::handed`], [`crate::roles::agent_preset`]), for the
39    /// person it acts for: the one place a device's delegation to its agent
40    /// becomes grants, so the device that admitted the agent and every
41    /// receiver of its changes decide it alike.
42    fn handed_preset(&self, workspace: &str) -> Vec<Grant> {
43        self.nodes()
44            .into_iter()
45            .filter(|node| node.handed)
46            .filter_map(|node| Some((node.member_id()?.as_agent()?, node.acted_for_person()?)))
47            .flat_map(|((agent, own), person)| {
48                crate::roles::agent_preset(workspace, (agent, own.as_str()), person)
49            })
50            .collect()
51    }
52}
53
54impl<'a> Authority<'a> {
55    /// The authority of `acting` under `policy`: an action is allowed only when
56    /// every node of its tree allows it.
57    ///
58    /// A person is decided by their grants and their role's; from a device that
59    /// is not theirs, by what such a device may do at most
60    /// ([`crate::Cap::FOREIGN_DEVICE`]). An agent or bot by the grants naming
61    /// it in the workspace and the ones its person gave it (`granted`). An
62    /// automation by what the people it runs for gave it.
63    #[must_use]
64    pub fn of_acting(
65        acting: &'a tilo_member_types::Acting,
66        policy: &'a WorkspacePolicy,
67        granted: &'a [Grant],
68    ) -> Self {
69        let mut people: usize = 0;
70        let mut person_parts = Vec::new();
71        let mut others = Vec::new();
72        // An automation acts with its owner's party: the tree names it for the
73        // person it runs for, and its steps are that person's grants. One that
74        // runs for nobody allows nothing.
75        let owned = !acting.acted_for.is_empty();
76        // The answers a person gave the agent session that caused the acting decide for the
77        // whole tree, as the agent's own do.
78        let answers: Vec<&Grant> = match &acting.cause {
79            Some(cause) => crate::session_answers(&policy.grants, cause.as_str()).collect(),
80            None => Vec::new(),
81        };
82        for node in acting.nodes() {
83            match &node.by {
84                Actor::Member(member) => match member {
85                    MemberId::Person(person) => {
86                        people = people.saturating_add(1);
87                        let party = policy
88                            .party(person.as_str())
89                            .with_grants(granted)
90                            .with_grants(answers.iter().copied());
91                        person_parts.push(if node.foreign_device {
92                            party.capped(crate::Cap::FOREIGN_DEVICE)
93                        } else {
94                            party
95                        });
96                    }
97                    MemberId::Agent { .. } | MemberId::Bot(_) => {
98                        others.push(
99                            software_party(member, policy, granted)
100                                .with_grants(answers.iter().copied()),
101                        );
102                    }
103                },
104                // A visitor holds what the workspace opens to any key, and nothing else.
105                Actor::Visitor(_) => others.push(policy.party_of(Grantee::AnyKey)),
106                Actor::Automation(_) if owned => {}
107                // An app acting by itself holds the grants naming it, never a person's.
108                Actor::Automation(_) => others.push(Party::default()),
109                // An app acting by itself, in the process its device launched as it, holds the
110                // grants naming it, with those its device hands it from its signed manifest.
111                Actor::App(app) => others.push(
112                    policy
113                        .party_of(Grantee::app(app.as_str()))
114                        .with_grants(granted),
115                ),
116            }
117        }
118        let mut parts = person_parts.into_iter().chain(others);
119        Self {
120            person: parts.next().unwrap_or_default(),
121            bounds: parts.collect(),
122            people,
123            app: acting.app.as_ref(),
124            app_kinds: None,
125            shortcut: None,
126        }
127    }
128}
129
130/// A member of `member` as a grant names it.
131#[must_use]
132pub fn granted_to(member: &MemberId) -> Grantee {
133    Grantee::Member(member.clone())
134}
135
136/// The grantee a grant names `actor` by, when it is a member: an automation is its owner's.
137#[must_use]
138pub fn grantee_of(actor: &tilo_member_types::Actor) -> Option<Grantee> {
139    Some(granted_to(actor.member_id()?))
140}
141
142/// An agent's or bot's own grants: the workspace's naming it, and those its
143/// acting carries (`granted`, what its certificate's delegation gives it). An
144/// agent is the pair of its id and the person it acts for, whom its
145/// certificate chains to: only the grants and answers naming that pair reach
146/// it, and once its person answered it ([`WorkspacePolicy::answers_narrow`]) what
147/// `granted` hands it decides nothing.
148fn software_party<'a>(
149    member: &MemberId,
150    policy: &'a WorkspacePolicy,
151    granted: &'a [Grant],
152) -> Party<'a> {
153    match member {
154        // A person's answer for their agent narrows it to what their answers name, whatever its
155        // delegation hands it.
156        MemberId::Agent { id, person } => {
157            policy.party_of_answered_agent(id, person.as_str(), granted)
158        }
159        member => policy.party_of(granted_to(member)).with_grants(granted),
160    }
161}
162
163/// One invocation, as admission weighs it.
164#[derive(Clone, Copy, Debug)]
165pub struct Invocation<'a> {
166    /// The action's node.
167    pub node: &'a TreePath,
168    /// The kind of action it is.
169    pub kind: tilo_action_types::ActionKind,
170    /// Whether it exercises authority over the workspace or others in it
171    /// ([`crate::Verdict::privileged`]).
172    pub privileged: bool,
173    /// Whether it needs its person attending.
174    pub attended: bool,
175    /// The node of the resource it changes, decided as well where it is one:
176    /// so a person restricted on one resource cannot change it through an
177    /// action they may otherwise take.
178    pub resource: Option<&'a TreePath>,
179    /// How far the invocation it continues was admitted to reach, when it
180    /// continues one: what goes further asks first.
181    pub ceiling: Option<Reach>,
182}
183
184/// The grants' answer for an action of `kind`, privileged when
185/// `privileged`, at `node`, for `authority` at `cx`, and the `Once` grants
186/// relying on it spends. A step going further than `ceiling` (the
187/// invocation it continues) is asked for as its own request.
188#[must_use]
189pub fn answer_at(
190    authority: &Authority<'_>,
191    (node, kind, privileged): (&TreePath, tilo_action_types::ActionKind, bool),
192    ceiling: Option<Reach>,
193    cx: &Context<'_>,
194) -> (Answer, Vec<GrantId>) {
195    let verdict = verdict_at(authority, (node, kind, privileged), ceiling, cx);
196    (verdict.answer, verdict.spent())
197}
198
199/// The verdict of `answer_at`, kept whole: what it was decided by, so admission can tell the
200/// answer a person gave in advance ([`Authority::answered_in_advance`]) from one asking them
201/// now.
202fn verdict_at<'a>(
203    authority: &'a Authority<'_>,
204    (node, kind, privileged): (&TreePath, tilo_action_types::ActionKind, bool),
205    ceiling: Option<Reach>,
206    cx: &Context<'_>,
207) -> crate::Verdict<'a> {
208    let mut verdict = authority.decide(node, kind, cx);
209    if privileged {
210        verdict = verdict.privileged();
211    }
212    let exceeds = ceiling.is_some_and(|ceiling| !ceiling.covers(kind, privileged));
213    if verdict.answer == Answer::Allow && exceeds {
214        verdict.answer = Answer::Ask;
215    }
216    verdict
217}
218
219/// Admit `invocation` for `authority`, asked of `asker`, at `cx`: whether
220/// it runs or asks first, and the `Once` grants admitting it spends.
221///
222/// # Errors
223/// Whose answer refused it.
224pub fn admit_invocation(
225    authority: &Authority<'_>,
226    asker: Asker,
227    invocation: Invocation<'_>,
228    cx: &Context<'_>,
229) -> Result<(Admission, Vec<GrantId>), Refused> {
230    let verdict = verdict_at(
231        authority,
232        (invocation.node, invocation.kind, invocation.privileged),
233        invocation.ceiling,
234        cx,
235    );
236    // What its person already answered for this very action or resource was not theirs to ask
237    // again, though it reaches outside the system: asking would put to them what they answered.
238    let answered_in_advance = authority.answered_in_advance(&verdict);
239    let answer = verdict.answer;
240    let spent = verdict.spent();
241    let resource = invocation.resource.map(|resource| {
242        answer_at(
243            authority,
244            (resource, invocation.kind, false),
245            invocation.ceiling,
246            cx,
247        )
248        .0
249    });
250    let admission = admit(
251        Invoked {
252            answer,
253            attended: invocation.attended,
254            outside: invocation.kind == tilo_action_types::ActionKind::Outside,
255            answered_in_advance,
256            resource,
257        },
258        asker,
259    )?;
260    Ok((admission, spent))
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use crate::{Answer, Context, Grant, Grantee, Role, SESSION_ANSWER_PREFIX, Verdict, roles};
267    use tilo_action_types::{ActionKind, KindSet};
268    use tilo_member_types::Acting;
269
270    const WORKSPACE: &str = "w";
271
272    fn policy() -> WorkspacePolicy {
273        let mut policy = WorkspacePolicy::new(WORKSPACE, "owner");
274        policy.members.insert("editor".into(), Role::Editor.into());
275        policy.members.insert("viewer".into(), Role::Viewer.into());
276        policy
277    }
278
279    fn app() -> TreePath {
280        TreePath::workspace(WORKSPACE).app("so.tilo.notes")
281    }
282
283    fn answer(
284        acting: &Acting,
285        policy: &WorkspacePolicy,
286        granted: &[Grant],
287        kind: ActionKind,
288    ) -> Answer {
289        Authority::of_acting(acting, policy, granted)
290            .decide(&app(), kind, &Context::at_secs(1))
291            .answer
292    }
293
294    tilo_test_env::scenario! {
295        fn whoever_acts_is_decided_by_every_party_it_acts_for;
296
297        phase a_person_is_decided_by_their_grants_and_their_roles;
298        {
299            let policy = policy();
300            assert_eq!(
301                answer(
302                    &Acting::person("editor"),
303                    &policy,
304                    &[],
305                    ActionKind::Undoable
306                ),
307                Answer::Allow
308            );
309            assert_eq!(
310                answer(
311                    &Acting::person("viewer"),
312                    &policy,
313                    &[],
314                    ActionKind::Undoable
315                ),
316                Answer::Deny
317            );
318        }
319
320        phase every_person_in_the_tree_has_to_allow_it;
321        {
322            let policy = policy();
323            // What the agent's turn gives it: reading and changing the workspace.
324            let turn = [Grant::new(
325                "turn:scribe:0",
326                Grantee::agent("scribe", "editor"),
327                TreePath::workspace(WORKSPACE),
328                KindSet::READ_UNDOABLE,
329                Answer::Allow,
330                Grantee::person("editor"),
331            )];
332            let agent_for_editor_and_owner = Acting::agent("scribe", "editor")
333                .acting_for(Acting::person("editor"))
334                .acting_for(Acting::person("owner"));
335            assert_eq!(
336                answer(
337                    &agent_for_editor_and_owner,
338                    &policy,
339                    &turn,
340                    ActionKind::Undoable
341                ),
342                Answer::Allow
343            );
344            let agent_for_a_viewer = agent_for_editor_and_owner.acting_for(Acting::person("viewer"));
345            assert_eq!(
346                answer(&agent_for_a_viewer, &policy, &turn, ActionKind::Undoable),
347                Answer::Deny,
348                "the viewer's grants decide too"
349            );
350        }
351
352        phase an_app_acting_by_itself_is_decided_by_the_grants_naming_it;
353        {
354            let app = Acting::by_app("so.tilo.notes");
355            assert_eq!(
356                answer(&app, &policy(), &[], ActionKind::Undoable),
357                Answer::Deny,
358                "an app holds no person's grants, the owner's included"
359            );
360            // Nor does the owner's device lend it theirs by signing what it wrote.
361            let own = TreePath::workspace(WORKSPACE).app("so.tilo.notes");
362            let signed = crate::MemberAccess::person(policy(), "owner")
363                .invoked_by(&app)
364                .expect("the owner's device writes for an app it runs");
365            assert_eq!(
366                signed.answer(&own, ActionKind::Undoable, &Context::at_secs(1)),
367                Answer::Deny,
368                "the device that signs an app's write bounds it, and grants it nothing"
369            );
370            // Installing Notes gave it its own records, and nothing beyond them.
371            let mut policy = policy();
372            policy.grants.push(crate::roles::app_records_grant(
373                WORKSPACE,
374                "so.tilo.notes",
375                "owner",
376            ));
377            assert_eq!(
378                answer(&app, &policy, &[], ActionKind::Undoable),
379                Answer::Allow
380            );
381            let elsewhere = TreePath::workspace(WORKSPACE)
382                .app("so.tilo.chat")
383                .kind("chat.messages");
384            assert_eq!(
385                Authority::of_acting(&app, &policy, &[])
386                    .decide(&elsewhere, ActionKind::Undoable, &Context::at_secs(1))
387                    .answer,
388                Answer::Deny,
389                "another app's records are no part of what installing gave"
390            );
391        }
392
393        phase an_agent_needs_its_own_grants_as_well_as_its_persons;
394        {
395            let mut policy = policy();
396            policy.grants.push(Grant::new(
397                "scribe-may-edit",
398                Grantee::agent("scribe", "editor"),
399                TreePath::workspace(WORKSPACE),
400                KindSet::READ_UNDOABLE,
401                Answer::Allow,
402                Grantee::person("editor"),
403            ));
404            let acting = Acting::agent("scribe", "editor").acting_for(Acting::person("editor"));
405            assert_eq!(
406                answer(&acting, &policy, &[], ActionKind::Undoable),
407                Answer::Allow
408            );
409            let unbounded = Acting::agent("other", "editor").acting_for(Acting::person("editor"));
410            assert_eq!(
411                answer(&unbounded, &policy, &[], ActionKind::Undoable),
412                Answer::Deny,
413                "an agent with no grants of its own does nothing"
414            );
415        }
416
417        phase an_agent_answering_someone_else_keeps_its_own_persons_refusal;
418        {
419            // The agent's certificate gives it the workspace; its own person, the owner, answers
420            // no for it on the whole workspace. Its turn answers the editor, through the owner.
421            let turn = [Grant::new(
422                "turn:scribe:0",
423                Grantee::agent("scribe", "owner"),
424                TreePath::workspace(WORKSPACE),
425                KindSet::READ_UNDOABLE,
426                Answer::Allow,
427                Grantee::person("owner"),
428            )];
429            let answering_the_editor = Acting::agent("scribe", "owner")
430                .acting_for(Acting::person("editor"))
431                .agent_of("owner");
432            assert_eq!(
433                answer(&answering_the_editor, &policy(), &turn, ActionKind::Undoable),
434                Answer::Allow,
435                "both people and the agent's certificate allow it"
436            );
437            let mut refusing = policy();
438            refusing.grants.push(crate::agent_answers::grant(
439                WORKSPACE,
440                ("scribe", "owner"),
441                (&crate::agent_answers::AnswerScope::Workspace, ActionKind::Undoable),
442                Answer::Deny,
443                Grantee::person("owner"),
444            ));
445            assert_eq!(
446                answer(&answering_the_editor, &refusing, &turn, ActionKind::Undoable),
447                Answer::Deny,
448                "what its own person answered for it refuses it, whoever's turn it answers"
449            );
450            let mut widening = refusing.clone();
451            // The editor answers only for an agent of their own: `scribe` of the editor is
452            // another agent.
453            widening.grants.push(crate::agent_answers::grant(
454                WORKSPACE,
455                ("scribe", "editor"),
456                (
457                    &crate::agent_answers::AnswerScope::app("so.tilo.notes"),
458                    ActionKind::Undoable,
459                ),
460                Answer::Allow,
461                Grantee::person("editor"),
462            ));
463            assert_eq!(
464                answer(&answering_the_editor, &widening, &turn, ActionKind::Undoable),
465                Answer::Deny,
466                "the more specific yes of the person a turn answers widens nothing the agent's own \
467                 person refused"
468            );
469        }
470
471        phase a_sessions_answers_decide_its_steps_and_no_other;
472        {
473            let session = "so.tilo.session/agent-session/release";
474            let mut policy = policy();
475            policy.grants.push(Grant::new(
476                "scribe-asks",
477                Grantee::agent("scribe", "editor"),
478                TreePath::workspace(WORKSPACE),
479                KindSet::READ_UNDOABLE,
480                Answer::Ask,
481                Grantee::person("editor"),
482            ));
483            policy.grants.push(Grant::new(
484                format!("{SESSION_ANSWER_PREFIX}{session}:app:so.tilo.notes:undoable"),
485                Grantee::agent("scribe", "editor"),
486                app(),
487                KindSet::UNDOABLE,
488                Answer::Allow,
489                Grantee::person("editor"),
490            ));
491            let run = Acting::agent("scribe", "editor")
492                .acting_for(Acting::person("editor"))
493                .caused_by(session);
494            assert_eq!(
495                answer(&run, &policy, &[], ActionKind::Undoable),
496                Answer::Allow,
497                "the person's answer for the session decides its steps"
498            );
499            let another = Acting::agent("scribe", "editor")
500                .acting_for(Acting::person("editor"))
501                .caused_by("so.tilo.session/agent-session/other");
502            assert_eq!(
503                answer(&another, &policy, &[], ActionKind::Undoable),
504                Answer::Ask,
505                "another session's answers decide nothing here"
506            );
507        }
508
509        phase an_automation_acts_with_its_owners_party_bounded_by_its_steps;
510        {
511            let policy = policy();
512            let automation = Acting::automation("1")
513                .acting_for(Acting::agent("scribe", "editor").acting_for(Acting::person("editor")));
514            let turn = [Grant::new(
515                "turn:scribe:0",
516                Grantee::agent("scribe", "editor"),
517                TreePath::workspace(WORKSPACE),
518                KindSet::READ_UNDOABLE,
519                Answer::Allow,
520                Grantee::person("editor"),
521            )];
522            assert_eq!(
523                answer(&automation, &policy, &turn, ActionKind::Undoable),
524                Answer::Allow,
525                "the tree's people and software decide; the automation is its owner's"
526            );
527            // A step it was given may narrow what it does there.
528            let mut granted = turn.to_vec();
529            granted.push(Grant::new(
530                "automation-1:outside",
531                Grantee::person("editor"),
532                TreePath::workspace(WORKSPACE),
533                KindSet::OUTSIDE,
534                Answer::Deny,
535                Grantee::person("editor"),
536            ));
537            assert_eq!(
538                answer(&automation, &policy, &granted, ActionKind::Outside),
539                Answer::Deny
540            );
541            let homeless = Acting::automation("1");
542            assert_eq!(
543                answer(&homeless, &policy, &turn, ActionKind::Undoable),
544                Answer::Deny,
545                "an automation that runs for nobody allows nothing"
546            );
547        }
548
549        phase a_device_that_is_not_theirs_governs_nothing_and_asks_before_reaching_out;
550        {
551            let policy = policy();
552            let foreign = Acting::person("owner").on_foreign_device(true);
553            assert_eq!(
554                answer(&foreign, &policy, &[], ActionKind::Outside),
555                Answer::Ask
556            );
557            let invite = roles::governance_action(WORKSPACE, roles::governance::ADD_MEMBER);
558            let verdict: Verdict<'_> = Authority::of_acting(&foreign, &policy, &[]).decide(
559                &invite,
560                roles::GOVERNANCE_KIND,
561                &Context::at_secs(1),
562            );
563            assert_eq!(verdict.answer, Answer::Deny, "never administers a workspace");
564            assert_eq!(
565                answer(&Acting::person("owner"), &policy, &[], ActionKind::Undoable),
566                Answer::Allow
567            );
568        }
569
570        phase an_app_reaches_only_the_kinds_it_declares_in_its_own_node;
571        {
572            let policy = policy();
573            let acting = Acting::person("editor").in_app("so.tilo.notes");
574            let kinds = ["notes.note".to_owned()];
575            let answer = |node: TreePath| {
576                Authority::of_acting(&acting, &policy, &[])
577                    .in_app(&kinds)
578                    .decide(&node, ActionKind::Undoable, &Context::at_secs(1))
579                    .answer
580            };
581            let own = TreePath::workspace(WORKSPACE).app("so.tilo.notes");
582            assert_eq!(answer(own.clone().kind("notes.note")), Answer::Allow);
583            assert_eq!(
584                answer(own.kind("notes.book")),
585                Answer::Deny,
586                "a kind the app does not declare is out of its reach"
587            );
588            assert_eq!(
589                answer(
590                    TreePath::workspace(WORKSPACE)
591                        .app("so.tilo.chat")
592                        .kind("chat.messages")
593                ),
594                Answer::Allow,
595                "in another app's node the person's own grants decide"
596            );
597        }
598
599        phase an_apps_own_connection_holds_the_grants_naming_it;
600        {
601            // An app's held connection acts as no person: it holds the grants that name the
602            // app, and an empty person's grants are nothing.
603            let app = "so.tilo.calendar";
604            let node = TreePath::workspace(WORKSPACE).app("tilo.accounts");
605            let granted = [Grant::new(
606                "manifest",
607                Grantee::app(app),
608                node.clone(),
609                tilo_action_types::KindSet::READ,
610                Answer::Allow,
611                Grantee::person("owner"),
612            )];
613            let holding = Acting::by_app(app).in_app(app);
614            assert_eq!(
615                Authority::of_acting(&holding, &policy(), &granted)
616                    .decide(&node, ActionKind::Read, &Context::at_secs(1))
617                    .answer,
618                Answer::Allow,
619                "the grant naming the app decides for its own connection"
620            );
621            // Someone acting through the app for nobody is not the app: it holds nothing.
622            let nobody = Acting::member(MemberId::person("")).in_app(app);
623            assert_eq!(
624                Authority::of_acting(&nobody, &policy(), &granted)
625                    .decide(&node, ActionKind::Read, &Context::at_secs(1))
626                    .answer,
627                Answer::Deny,
628                "nobody acting through the app borrows its grants"
629            );
630            assert_eq!(
631                Authority::of_acting(&holding, &policy(), &[])
632                    .decide(&node, ActionKind::Read, &Context::at_secs(1))
633                    .answer,
634                Answer::Deny,
635                "and nothing reaches it that names no one"
636            );
637        }
638
639        phase a_tree_asks_the_person_unless_someone_acts_for_them;
640        {
641            let person = Acting::person("editor");
642            assert!(person.asker(true).reachable);
643            assert!(!person.asker(true).delegated);
644            let agent = Acting::agent("scribe", "editor").acting_for(Acting::person("editor"));
645            assert!(agent.asker(true).delegated);
646            assert!(
647                !agent.asker(false).reachable,
648                "with nobody to ask, an ask refuses"
649            );
650        }
651    }
652
653    tilo_test_env::scenario! {
654        fn a_persons_answer_in_advance_lifts_the_ask_of_what_their_agent_sends;
655
656        phase an_agents_send_asks_its_person;
657        {
658            let policy = policy();
659            let turn = [
660                Grant::new(
661                    "turn:scribe:0",
662                    Grantee::agent("scribe", "editor"),
663                    TreePath::workspace(WORKSPACE),
664                    KindSet::READ_UNDOABLE,
665                    Answer::Allow,
666                    Grantee::person("editor"),
667                ),
668                Grant::new(
669                    "turn:scribe:1",
670                    Grantee::agent("scribe", "editor"),
671                    TreePath::workspace(WORKSPACE),
672                    KindSet::OUTSIDE,
673                    Answer::Ask,
674                    Grantee::person("editor"),
675                ),
676            ];
677            let acting = Acting::agent("scribe", "editor").acting_for(Acting::person("editor"));
678            let send = TreePath::workspace(WORKSPACE)
679                .app("so.tilo.notes")
680                .kind("note")
681                .resource("n1")
682                .action("send");
683            let asked = |turn: &[Grant]| {
684                admit_invocation(
685                    &Authority::of_acting(&acting, &policy, turn),
686                    Asker {
687                        reachable: true,
688                        delegated: true,
689                    },
690                    Invocation {
691                        node: &send,
692                        kind: ActionKind::Outside,
693                        privileged: false,
694                        attended: false,
695                        resource: None,
696                        ceiling: None,
697                    },
698                    &Context::at_secs(1),
699                )
700                .expect("it is admitted, or asks")
701                .0
702            };
703            assert_eq!(
704                asked(&turn),
705                Admission::AsksFirst,
706                "an agent's send waits for its person"
707            );
708
709            // The person's own "Always allow this" for that very action lifts the ask.
710            let scope = crate::agent_answers::AnswerScope::action("so.tilo.notes", "note", "send");
711            let mut answered = turn.to_vec();
712            answered.push(crate::agent_answers::grant(
713                WORKSPACE,
714                ("scribe", "editor"),
715                (&scope, ActionKind::Outside),
716                Answer::Allow,
717                Grantee::person("editor"),
718            ));
719            assert_eq!(
720                asked(&answered),
721                Admission::Runs,
722                "what its person answered in advance runs unasked"
723            );
724
725            // An answer for another action is no answer for this one.
726            let elsewhere =
727                crate::agent_answers::AnswerScope::action("so.tilo.notes", "note", "archive");
728            let mut other = turn.to_vec();
729            other.push(crate::agent_answers::grant(
730                WORKSPACE,
731                ("scribe", "editor"),
732                (&elsewhere, ActionKind::Outside),
733                Answer::Allow,
734                Grantee::person("editor"),
735            ));
736            assert_eq!(
737                asked(&other),
738                Admission::AsksFirst,
739                "only an answer for that very action lifts its ask"
740            );
741        }
742
743        phase an_attended_action_its_person_answered_in_advance_runs_unasked_too;
744        {
745            let policy = policy();
746            let mut turn = vec![Grant::new(
747                "turn:scribe:0",
748                Grantee::agent("scribe", "editor"),
749                TreePath::workspace(WORKSPACE),
750                KindSet::READ_UNDOABLE,
751                Answer::Allow,
752                Grantee::person("editor"),
753            )];
754            let acting = Acting::agent("scribe", "editor").acting_for(Acting::person("editor"));
755            let act = TreePath::workspace(WORKSPACE)
756                .app("so.tilo.notes")
757                .kind("note")
758                .resource("n1")
759                .action("edit");
760            let admission = |turn: &[Grant]| {
761                admit_invocation(
762                    &Authority::of_acting(&acting, &policy, turn),
763                    Asker {
764                        reachable: true,
765                        delegated: true,
766                    },
767                    Invocation {
768                        node: &act,
769                        kind: ActionKind::Undoable,
770                        privileged: false,
771                        attended: true,
772                        resource: None,
773                        ceiling: None,
774                    },
775                    &Context::at_secs(1),
776                )
777                .expect("it is admitted, or asks")
778                .0
779            };
780            assert_eq!(admission(&turn), Admission::AsksFirst);
781            let scope = crate::agent_answers::AnswerScope::action("so.tilo.notes", "note", "edit");
782            turn.push(crate::agent_answers::grant(
783                WORKSPACE,
784                ("scribe", "editor"),
785                (&scope, ActionKind::Undoable),
786                Answer::Allow,
787                Grantee::person("editor"),
788            ));
789            assert_eq!(
790                admission(&turn),
791                Admission::Runs,
792                "an attended action its person answered in advance runs unasked"
793            );
794        }
795    }
796}