Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/al-test-cli/tests/suite/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ mod provider_no_row_7392;
mod query_close_error_last_error;
mod query_outer_flow;
mod query_reopen_rows_left;
mod query_static_save_permission;
mod quoted_ident;
mod r1b_page_moves;
mod readable_messages;
Expand Down Expand Up @@ -237,6 +238,7 @@ mod test_framework_refusals;
mod test_handlers;
mod testpage_action_without_parentheses;
mod this_in_objects;
mod trigger_setup_read_permission;
mod typed_handler_set_up_variable;
mod typed_handler_temp_stored_source;
mod unpinned_error_result;
Expand Down
84 changes: 84 additions & 0 deletions crates/al-test-cli/tests/suite/query_static_save_permission.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//! A static `Query.SaveAsCsv(Number, OutStream)` and `Query.SaveAsXml(Number, OutStream)` under a restricted set check the
//! query of that number, not the query of the last instance call in the session (al-runner issue 7612). The check is the one
//! `Query.Open` takes (Y24PermExecute.al:62-63, Query Execute denied).

use super::y48_platform_probes::{outcomes, outcomes_edited};
use al_test_cli::report::Outcome;

const SRC: &str = r#"
dotnet { assembly("Microsoft.Dynamics.Nav.PermissionTestHelper") {
type("Microsoft.Dynamics.Nav.Runtime.PermissionTestHelper"; "PermissionTestHelper") { } } }
table 50100 "Q Row" { fields { field(1; Id; Integer) { } field(2; Data; Blob) { } } keys { key(PK; Id) { Clustered = true; } } }
query 50100 "Granted Q" { elements { dataitem(R; "Q Row") { column(Id; Id) { } } } }
query 50101 "Denied Q" { elements { dataitem(R; "Q Row") { column(Id; Id) { } } } }
permissionset 50100 "NARROW" { Assignable = true; Permissions = tabledata "Q Row" = R, query "Granted Q" = X, codeunit T = X; }
codeunit 50000 T { Subtype = Test; TestPermissions = Disabled;
local procedure Restrict() var H: DotNet PermissionTestHelper; begin
H := H.PermissionTestHelper(); H.AddEffectivePermissionSet('NARROW'); end;
[Test] procedure CsvOfDeniedFirst() var Row: Record "Q Row" temporary; OutS: OutStream; begin
Restrict(); Row.Data.CreateOutStream(OutS);
asserterror Query.SaveAsCsv(Query::"Denied Q", OutS); Error(GetLastErrorCode()); end;
[Test] procedure CsvOfDeniedAfterGranted() var Row: Record "Q Row" temporary; Q: Query "Granted Q"; OutS: OutStream; begin
Restrict(); Q.Open(); Q.Close(); Row.Data.CreateOutStream(OutS);
asserterror Query.SaveAsCsv(Query::"Denied Q", OutS); Error(GetLastErrorCode()); end;
[Test] procedure XmlOfDeniedAfterGranted() var Row: Record "Q Row" temporary; Q: Query "Granted Q"; OutS: OutStream; begin
Restrict(); Q.Open(); Q.Close(); Row.Data.CreateOutStream(OutS);
asserterror Query.SaveAsXml(Query::"Denied Q", OutS); Error(GetLastErrorCode()); end;
[Test] procedure CsvOfGranted() var Row: Record "Q Row" temporary; OutS: OutStream; begin
Restrict(); Row.Data.CreateOutStream(OutS);
if Query.SaveAsCsv(Query::"Granted Q", OutS) then Error('saved'); Error('not saved'); end;
}
"#;

#[test]
fn static_save_as_checks_the_query_of_its_number() {
let o = outcomes(SRC);
let get = |name: &str| {
&o.iter()
.find(|(n, _)| n == name)
.unwrap_or_else(|| panic!("{name} in {o:?}"))
.1
};
for name in ["CsvOfDeniedFirst", "CsvOfDeniedAfterGranted", "XmlOfDeniedAfterGranted"] {
assert_eq!(*get(name), Outcome::Fail("DB:ExecuteObjDenied".into()), "{name}");
}
assert_eq!(*get("CsvOfGranted"), Outcome::Fail("saved".into()));
}

const SHELL_SRC: &str = r#"
table 50100 "Q Row" { fields { field(1; Id; Integer) { } field(2; Data; Blob) { } } keys { key(PK; Id) { Clustered = true; } } }
query 50102 "Shell Q" { elements { dataitem(R; "Q Row") { column(Id; Id) { } } } }
codeunit 50000 T { Subtype = Test;
[Test] procedure CsvOfShell() var Row: Record "Q Row" temporary; OutS: OutStream; begin
Row.Data.CreateOutStream(OutS); if Query.SaveAsCsv(50102, OutS) then Error('saved'); Error('not saved'); end;
[Test] procedure XmlOfShell() var Row: Record "Q Row" temporary; OutS: OutStream; begin
Row.Data.CreateOutStream(OutS); if Query.SaveAsXml(50102, OutS) then Error('saved'); Error('not saved'); end;
[Test] procedure CsvOfUnknown() var Row: Record "Q Row" temporary; OutS: OutStream; begin
Row.Data.CreateOutStream(OutS); if Query.SaveAsCsv(50199, OutS) then Error('saved'); Error('not saved'); end;
}
"#;

/// A query of a dependency app that was not compiled is refused (BC finds it); an unknown id keeps main's No
/// (xmlports/import/XpTQuerySave.al:SaveAsCsv_UnknownQueryId) unless the run skipped a dependency app.
#[test]
fn static_save_as_of_an_uncompiled_or_skipped_query_refuses() {
let shell = |p: &mut al_ir::Program| {
let i = p.objects.iter().position(|o| o.name == "Shell Q").expect("Shell Q");
p.objects[i].uncompiled = true;
};
let o = outcomes_edited(SHELL_SRC, shell, Vec::new());
let get = |o: &[(String, Outcome)], name: &str| o.iter().find(|(n, _)| n == name).expect(name).1.clone();
for name in ["CsvOfShell", "XmlOfShell"] {
match get(&o, name) {
Outcome::NotRun(why) => assert!(why.contains("was not compiled"), "{name}: {why}"),
other => panic!("{name}: {other:?}"),
}
}
assert_eq!(get(&o, "CsvOfUnknown"), Outcome::Fail("not saved".into()));
let o = outcomes_edited(SHELL_SRC, |_| {}, vec!["`Dep` by Publisher".into()]);
match get(&o, "CsvOfUnknown") {
Outcome::NotRun(why) => assert!(why.contains("skipped the dependency"), "{why}"),
other => panic!("{other:?}"),
}
assert_eq!(get(&o, "CsvOfShell"), Outcome::Fail("saved".into()));
}
70 changes: 70 additions & 0 deletions crates/al-test-cli/tests/suite/trigger_setup_read_permission.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//! The read Base Application's "API Webhook Notification Mgt." (codeunit 6153) makes while it answers
//! `Global Triggers.GetDatabaseTableTriggerSetup` under a restricted set: `IsEmpty` of "API Webhook Subscription" with no row
//! passes (permissions/SysFlowFieldPerm.al:489-499). Every neighbor keeps main's refusal: a table with a row, another
//! method, another caller, and a codeunit 6153 of an app that is not Base Application.

use super::y48_platform_probes::outcomes_with_hits_app;
use al_test_cli::report::Outcome;

/// An app with an own table, a subscriber `caller` whose setup answer runs `body`, a set that grants the own table and runs
/// both codeunits but does not grant "API Webhook Subscription", and a test that writes the own table under that set. `seed` runs before the set applies.
fn src(caller: &str, body: &str, seed: &str) -> String {
let id = caller.split_whitespace().nth(1).expect("codeunit id");
format!(
r#"
dotnet {{ assembly("Microsoft.Dynamics.Nav.PermissionTestHelper") {{
type("Microsoft.Dynamics.Nav.Runtime.PermissionTestHelper"; "PermissionTestHelper") {{ }} }} }}
table 50100 "Own Row" {{ fields {{ field(1; Id; Integer) {{ }} }} keys {{ key(PK; Id) {{ Clustered = true; }} }} }}
{caller}
{{
[EventSubscriber(ObjectType::Codeunit, Codeunit::"Global Triggers", GetDatabaseTableTriggerSetup, '', false, false)]
local procedure GetDatabaseTableTriggerSetup(TableId: Integer; var OnDatabaseInsert: Boolean; var OnDatabaseModify: Boolean; var OnDatabaseDelete: Boolean; var OnDatabaseRename: Boolean)
var Sub: Record "API Webhook Subscription";
begin
{body}
end;
}}
permissionset 50100 "NARROW" {{ Assignable = true; Permissions = tabledata "Own Row" = RIMD, codeunit T = X, codeunit {id} = X; }}
codeunit 50000 T {{ Subtype = Test; TestPermissions = Disabled;
[Test] procedure WriteOwn() var H: DotNet PermissionTestHelper; Row: Record "Own Row"; Sub: Record "API Webhook Subscription"; begin
{seed}
H := H.PermissionTestHelper(); H.AddEffectivePermissionSet('NARROW');
Row.Id := 1; Row.Insert(); end;
}}
"#
)
}

const MGT: &str = r#"codeunit 6153 "API Webhook Notification Mgt.""#;
const OTHER: &str = r#"codeunit 50101 "Other Setup""#;
const IS_EMPTY: &str = "if Sub.IsEmpty() then;";

fn outcome(app_id: &str, src: &str) -> Outcome {
let o = outcomes_with_hits_app(app_id, src, "T");
o.into_iter().find(|(n, _, _)| n == "WriteOwn").expect("WriteOwn").1
}

fn refused(o: Outcome, what: &str) {
match o {
Outcome::NotRun(why) => assert!(why.contains("system table"), "{what}: {why}"),
other => panic!("{what}: expected main's refusal, got {other:?}"),
}
}

#[test]
fn setup_read_of_an_empty_table_by_base_application_passes() {
let base = al_ir::BASE_APPLICATION_APP_ID;
assert_eq!(outcome(base, &src(MGT, IS_EMPTY, "")), Outcome::Pass);
}

#[test]
fn setup_read_neighbors_keep_the_refusal() {
let base = al_ir::BASE_APPLICATION_APP_ID;
refused(
outcome(base, &src(MGT, IS_EMPTY, "Sub.Init(); Sub.Insert();")),
"table with a row",
);
refused(outcome(base, &src(MGT, "if Sub.FindFirst() then;", "")), "FindFirst");
refused(outcome(base, &src(OTHER, IS_EMPTY, "")), "another caller");
refused(outcome("main", &src(MGT, IS_EMPTY, "")), "codeunit 6153 of another app");
}
27 changes: 27 additions & 0 deletions crates/al-test-cli/tests/suite/y48_platform_probes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,32 @@ pub(crate) fn outcomes_with_hits_app(

/// `main` as the app `app_id` on the System app, compiled, and an engine for it that runs as BC 27.5.
fn compile_on_system(app_id: &str, main: &str) -> (std::sync::Arc<Engine>, al_sema::lower::Lowered) {
compile_on_system_edited(app_id, main, |_| {})
}

/// [`outcomes`] of a program changed by `edit` before the engine is made, with `skipped` as the dependency apps the run
/// skipped (`Engine::skipped_apps`): for shapes a source alone does not make, such as a shell of an uncompiled app.
pub(crate) fn outcomes_edited(
main: &str,
edit: impl FnOnce(&mut al_ir::Program),
skipped: Vec<String>,
) -> Vec<(String, Outcome)> {
let (mut engine, l) = compile_on_system_edited("main", main, edit);
std::sync::Arc::get_mut(&mut engine).expect("not shared").skipped_apps = skipped;
let oi = l
.program
.objects
.iter()
.position(|o| o.name == "T")
.expect("test codeunit T");
run_codeunit(&engine, &l, oi)
}

fn compile_on_system_edited(
app_id: &str,
main: &str,
edit: impl FnOnce(&mut al_ir::Program),
) -> (std::sync::Arc<Engine>, al_sema::lower::Lowered) {
use al_sema::workspace::{AppKind, AppSource};
let app = |id: &str, name: &str, files: Vec<(String, String)>| AppSource {
id: id.into(),
Expand Down Expand Up @@ -106,6 +132,7 @@ fn compile_on_system(app_id: &str, main: &str) -> (std::sync::Arc<Engine>, al_se
for a in program.apps.iter_mut().filter(|a| a.version.is_empty()) {
a.version = "1.0.0.0".into();
}
edit(&mut program);
let engine = Engine::with_target(
std::sync::Arc::new(program),
blocked,
Expand Down
2 changes: 2 additions & 0 deletions crates/al-vm/src/globaltriggers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,9 @@ impl Session {
sender: None,
};
self.events.setup_no_ops = self.setup_subscribers_changing_nothing(id);
let outer = self.events.db_setup_table.replace(table);
let raised = self.raise_global(&call, &mut args);
self.events.db_setup_table = outer;
self.events.setup_no_ops.clear();
if let Err(e) = raised {
self.events.global_setups.remove(&table);
Expand Down
2 changes: 0 additions & 2 deletions crates/al-vm/src/install_left.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,6 @@ impl Session {
report_refusal_after_denial: _,
permission_caller: _,
permission_run_object: _,
// Set before each query method call that reads it.
query_object: _,
query_receiver: _,
keyref_receiver_local: _,
test_object: _,
Expand Down
2 changes: 2 additions & 0 deletions crates/al-vm/src/install_left/clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ pub(super) fn events_as_new(e: &EventState) -> bool {
install_written,
install_rows,
setup_no_ops,
db_setup_table,
trial,
global_setups,
} = e;
Expand Down Expand Up @@ -161,6 +162,7 @@ pub(super) fn events_as_new(e: &EventState) -> bool {
&& install_written.is_none()
&& install_rows.is_none()
&& setup_no_ops.is_empty()
&& db_setup_table.is_none()
&& !allowed
&& picked.is_empty()
&& *depth == 0
Expand Down
5 changes: 2 additions & 3 deletions crates/al-vm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ mod partial;
mod permission_bulk_no_match;
mod permission_shadow;
mod permission_system_flowfield;
mod permission_trigger_setup;
mod permission_triggers;
mod permissions;
mod platform;
Expand Down Expand Up @@ -1064,8 +1065,6 @@ pub struct Session {
pub(crate) permission_caller: Option<usize>,
/// The xmlport whose export runs: the reads the runtime makes for it (not AL code) are decided as that object's.
pub(crate) permission_run_object: Option<usize>,
/// The query whose method runs (the object index), for the read check of `query_rows`.
pub(crate) query_object: usize,
/// The global variable (object index of the routine, slot) a query method is called on, from `run_native` to `query_op`.
pub(crate) query_receiver: Option<(usize, usize)>,
/// The KeyRef method that runs was called on a declared local variable of a codeunit procedure, from `run_native` to
Expand Down Expand Up @@ -1454,7 +1453,6 @@ impl Session {
report_refusal_after_denial: None,
permission_caller: None,
permission_run_object: None,
query_object: 0,
query_receiver: None,
keyref_receiver_local: false,
permissions: None,
Expand Down Expand Up @@ -1516,6 +1514,7 @@ impl Session {
install_written: None,
install_rows: None,
setup_no_ops: Default::default(),
db_setup_table: None,
trial: Default::default(),
global_setups: Default::default(),
},
Expand Down
56 changes: 56 additions & 0 deletions crates/al-vm/src/permission_trigger_setup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//! A read that the code answering `Global Triggers.GetDatabaseTableTriggerSetup` makes under a restricted set, which the
//! session's sets do not grant (ADR-062). Only the measured read runs: Base Application's `API Webhook Notification Mgt.`
//! asks `IsEmpty` of "API Webhook Subscription" when the first write of an own table under a Permissions Mock set asks the
//! table's setup, and that table holds no row. BC raises no error there and the write goes on
//! (permissions/SysFlowFieldPerm.al:489-499: `Item.DeleteAll` of `Op`, the first write of "SFP Item" in each case, under
//! "SFP PA READ" and "SFP NO PA", neither of which grants the table). With no row, the table enables no database trigger
//! whichever way BC answers the read. Every other read keeps the refusal of `Session::write_denied`.

use crate::Session;
use crate::permissions::{Access, Op};
use crate::records::Rec;
use al_builtins::native::Signal;
use al_builtins::record_op::RecordOp;

/// "API Webhook Subscription".
const API_WEBHOOK_SUBSCRIPTION: u32 = 2_000_000_095;
/// Base Application's "API Webhook Notification Mgt.", whose `GetDatabaseTableTriggerSetup` reads it.
const API_WEBHOOK_NOTIFICATION_MGT: u32 = 6153;

impl Session {
/// Whether the denied `access` by the record method `method` on `rec` is the measured read above. Every fact is
/// required by equality: the setup of a table is being asked (`EventState::db_setup_table`), the method is `IsEmpty`,
/// the access a read of "API Webhook Subscription", the running code is codeunit 6153 of Base Application, and the table holds no row in
/// the record's company.
pub(crate) fn trigger_setup_read_unchecked(
&mut self,
method: RecordOp,
rec: &Rec,
access: Access,
) -> Result<bool, Signal> {
let program = &self.engine.program;
let heads = program.objects.heads();
let caller_is_mgt = self.frames.last().is_some_and(|&o| {
heads[o].is_kind(al_ir::ObjKind::Codeunit)
&& heads[o].id == Some(API_WEBHOOK_NOTIFICATION_MGT)
&& program
.apps
.get(program.objects[o].app as usize)
.is_some_and(|a| a.id.eq_ignore_ascii_case(al_ir::BASE_APPLICATION_APP_ID))
});
let measured = self.events.db_setup_table.is_some()
&& method == RecordOp::IsEmpty
&& access.op == Op::Read
&& access.kind == 0
&& access.id == API_WEBHOOK_SUBSCRIPTION
&& caller_is_mgt;
if !measured {
return Ok(false);
}
let t = self.table(rec)?;
let cx = self.cx_for(rec, &t)?;
let rows = al_data::Store::count(&*self.store_for(rec)?, &cx, &t, &[])
.map_err(|e| Signal::unsupported(format!("store error {e}")))?;
Ok(rows == 0)
}
}
3 changes: 3 additions & 0 deletions crates/al-vm/src/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1592,6 +1592,9 @@ impl Session {
if !from_al {
return refuse("made by the runtime for a page, report, xmlport or validation; ADR-062 probes P16-P18");
}
if access.op == Op::Read && self.trigger_setup_read_unchecked(method, rec, access)? {
return Ok(());
}
if access.id >= 2_000_000_000 && access.id != TENANT_MEDIA {
return refuse("on a system table; probe P13 pins Tenant Media only");
}
Expand Down
Loading
Loading