1use std::collections::{BTreeMap, HashMap};
15
16use bynk_project::{ParsedFile, UnitKind};
17use bynk_syntax::ast::{
18 ActorDecl, BinOp, CommonsItem, Expr, ExprKind, Handler, HandlerKind, SourceUnit, UnaryOp,
19 expr_children, statement_exprs,
20};
21use bynk_syntax::error::CompileError;
22use bynk_syntax::span::Span;
23
24use crate::actors::{caller_refinement, dotted_name};
25use crate::checker::Callee;
26use crate::project_model::{ErrorSink, UnitCallees};
27use crate::symbols::UnitTable;
28
29fn mentioned_names(e: &Expr, out: &mut Vec<(String, Span)>) {
31 match &e.kind {
32 ExprKind::Paren(inner) | ExprKind::UnaryOp(UnaryOp::Not, inner) => {
33 mentioned_names(inner, out)
34 }
35 ExprKind::BinOp(BinOp::And | BinOp::Or, l, r) => {
36 mentioned_names(l, out);
37 mentioned_names(r, out);
38 }
39 ExprKind::Call { name, args, .. } if name.name == "IsContext" => {
40 out.extend(
41 args.iter()
42 .filter_map(|a| dotted_name(a).map(|n| (n, a.span))),
43 );
44 }
45 _ => {}
46 }
47}
48
49fn actor_admits(name: &str, table: &UnitTable, from: &str) -> bool {
54 match table.actors.get(name) {
55 Some(decl) => match caller_refinement(decl, &table.actors) {
56 Some(pred) => pred.admits(from),
57 None => {
58 decl.auth
59 .as_ref()
60 .and_then(|a| crate::actors::Scheme::from_name(&a.name))
61 != Some(crate::actors::Scheme::Foreign)
62 }
63 },
64 None => true,
65 }
66}
67
68fn admitted_note(
70 by_names: &[&str],
71 table: &UnitTable,
72 contexts: &[&str],
73 caller: &str,
74) -> (String, String) {
75 let admitted: Vec<&str> = contexts
76 .iter()
77 .copied()
78 .filter(|c| by_names.iter().any(|n| actor_admits(n, table, c)))
79 .collect();
80 let actor = by_names.join(" | ");
81 let list = if admitted.is_empty() {
82 "no context".to_string()
83 } else {
84 admitted
85 .iter()
86 .map(|c| format!("`{c}`"))
87 .collect::<Vec<_>>()
88 .join(", ")
89 };
90 let _ = caller;
91 (actor, list)
92}
93
94pub fn phase_caller_admission(
96 parsed: &[ParsedFile],
97 groups: &BTreeMap<String, Vec<usize>>,
98 kinds: &BTreeMap<String, UnitKind>,
99 unit_tables: &HashMap<String, UnitTable>,
100 unit_callees: &UnitCallees,
101 errors: &mut ErrorSink,
102) {
103 let contexts: Vec<&str> = groups
104 .keys()
105 .filter(|n| kinds.get(*n) == Some(&UnitKind::Context))
106 .map(String::as_str)
107 .collect();
108 for (ctx_name, indices) in groups {
109 if kinds.get(ctx_name) != Some(&UnitKind::Context) {
110 continue;
111 }
112 for &i in indices {
113 let SourceUnit::Context(ctx) = parsed[i].unit() else {
114 continue;
115 };
116 let file = parsed[i].identity_path();
117 for item in &ctx.items {
118 match item {
119 CommonsItem::Actor(a) => check_actor_names(a, &contexts, &file, errors),
120 CommonsItem::Service(s) => {
121 for h in &s.handlers {
122 check_handler_calls(
123 h,
124 ctx_name,
125 &contexts,
126 unit_tables,
127 unit_callees,
128 &file,
129 errors,
130 );
131 }
132 }
133 CommonsItem::Agent(a) => {
134 for h in &a.handlers {
135 check_handler_calls(
136 h,
137 ctx_name,
138 &contexts,
139 unit_tables,
140 unit_callees,
141 &file,
142 errors,
143 );
144 }
145 }
146 _ => {}
147 }
148 }
149 }
150 }
151}
152
153fn check_actor_names(
154 actor: &ActorDecl,
155 contexts: &[&str],
156 file: &std::path::Path,
157 errors: &mut ErrorSink,
158) {
159 let Some(r) = &actor.refinement else {
160 return;
161 };
162 let mut names = Vec::new();
163 mentioned_names(&r.predicate, &mut names);
164 for (name, span) in names {
165 if contexts.contains(&name.as_str()) {
166 continue;
167 }
168 let mut err = CompileError::new(
169 "bynk.actor.unknown_context",
170 span,
171 format!("`{name}` is not a context of this project"),
172 )
173 .with_note("`IsContext(…)` names the project's own contexts, written as qualified names");
174 if let Some(near) = bynk_project::paths::did_you_mean(&name, contexts.iter().copied()) {
175 err = err.with_note(format!("did you mean `{near}`?"));
176 }
177 errors.push_for(Some(file), err);
178 }
179}
180
181fn check_handler_calls(
182 handler: &Handler,
183 caller: &str,
184 contexts: &[&str],
185 unit_tables: &HashMap<String, UnitTable>,
186 unit_callees: &UnitCallees,
187 file: &std::path::Path,
188 errors: &mut ErrorSink,
189) {
190 let Some(callees) = unit_callees.get(caller) else {
191 return;
192 };
193 let mut stack: Vec<&Expr> = Vec::new();
194 for s in &handler.body.statements {
195 statement_exprs(s, &mut stack);
196 }
197 stack.push(&handler.body.tail);
198 while let Some(e) = stack.pop() {
199 if let Some(Callee::Cross { unit, service }) = callees.get(&e.id)
200 && let Some(table) = unit_tables.get(unit)
201 && let Some(svc) = table.services.get(service)
202 && let Some(h) = svc.handlers.iter().find(|h| h.kind == HandlerKind::Call)
203 && let Some(by) = h.by_clause.as_ref().or(svc.default_by.as_ref())
204 {
205 let names: Vec<&str> = by.actors.iter().map(|a| a.name.as_str()).collect();
206 let refined = names.iter().any(|n| {
209 table
210 .actors
211 .get(*n)
212 .is_some_and(|d| caller_refinement(d, &table.actors).is_some())
213 });
214 if refined && !names.iter().any(|n| actor_admits(n, table, caller)) {
215 let (actor, admitted) = admitted_note(&names, table, contexts, caller);
216 errors.push_for(
217 Some(file),
218 CompileError::new(
219 "bynk.actor.caller_not_admitted",
220 e.span,
221 format!("`{unit}.{service}` does not admit calls from `{caller}`"),
222 )
223 .with_note(format!(
224 "its handler is guarded by `by {actor}`, which admits {admitted}"
225 )),
226 );
227 }
228 }
229 stack.extend(expr_children(e));
230 }
231}
232
233#[cfg(test)]
234mod tests {
235 use crate::testkit::analyse;
236
237 const BILLING: &str = "context shop.billing\n\n\
238actor Admin = Caller where IsContext(shop.admin)\n\
239actor NotLegacy = Caller where !IsContext(shop.legacy)\n\n\
240service refunds {\n on call(id: String) -> Effect[Int] by Admin {\n Effect.pure(1)\n }\n}\n\n\
241service status {\n on call(id: String) -> Effect[Int] by NotLegacy {\n Effect.pure(2)\n }\n}\n";
242
243 fn caller(name: &str, call: &str) -> (String, String) {
244 (
245 format!("shop/{name}.bynk"),
246 format!(
247 "context shop.{name}\n\nconsumes shop.billing\n\n\
248service go {{\n on call(id: String) -> Effect[Int] by Caller {{\n {call}\n }}\n}}\n"
249 ),
250 )
251 }
252
253 fn project(callers: &[(&str, &str)]) -> crate::testkit::Analysed {
254 let mut files: Vec<(String, String)> =
255 vec![("shop/billing.bynk".to_string(), BILLING.to_string())];
256 for name in ["admin", "legacy", "orders"] {
257 let call = callers
258 .iter()
259 .find(|(n, _)| *n == name)
260 .map_or("Effect.pure(0)", |(_, c)| *c);
261 files.push(caller(name, call));
262 }
263 let refs: Vec<(&str, &str)> = files
264 .iter()
265 .map(|(a, b)| (a.as_str(), b.as_str()))
266 .collect();
267 analyse(&refs)
268 }
269
270 #[test]
271 fn an_admitted_context_calls_clean() {
272 project(&[("admin", "shop.billing.refunds(id)")]).assert_clean();
273 }
274
275 #[test]
276 fn a_context_the_predicate_does_not_name_is_refused_at_the_call() {
277 let a = project(&[("orders", "shop.billing.refunds(id)")]);
278 assert_eq!(a.error_categories(), ["bynk.actor.caller_not_admitted"]);
279 }
280
281 #[test]
282 fn a_deny_list_refuses_only_the_named_context() {
283 project(&[("orders", "shop.billing.status(id)")]).assert_clean();
284 let a = project(&[("legacy", "shop.billing.status(id)")]);
285 assert_eq!(a.error_categories(), ["bynk.actor.caller_not_admitted"]);
286 }
287
288 #[test]
289 fn a_name_that_is_no_context_is_refused() {
290 let a = analyse(&[("shop/billing.bynk", BILLING)]);
292 assert_eq!(
293 a.error_categories(),
294 ["bynk.actor.unknown_context", "bynk.actor.unknown_context"]
295 );
296 }
297}