Co-locate AL samples next to their knowledge articles

The /samples/ top-level tree is replaced with sibling files in each
knowledge-layer folder. An article and its demonstrations now live
side-by-side:

  microsoft/knowledge/<domain>/<slug>.md
  microsoft/knowledge/<domain>/<slug>.good.al
  microsoft/knowledge/<domain>/<slug>.bad.al

Rationale:
- Proximity. An article and its paired samples are one unit; the
  filesystem now reflects that.
- Layer ownership. Samples inherit layer precedence for free -- a
  /custom/ fork can override an article and its samples atomically,
  which the shared /samples/ tree previously made awkward.
- Trivial migration path. Action-skill source globs
  (*/knowledge/<domain>/**/*.md) are unchanged; sample discovery is a
  sibling-filename lookup.

Changes:
- git mv of all 65 sample files from samples/<domain>/<slug>/{bad,good}.al
  to microsoft/knowledge/<domain>/<slug>.{bad,good}.al (history preserved).
- Update See-sample references in all 37 articles that ship samples.
- skills/read.md: replace the no-code-blocks bullet with a pointer to a
  new Sample files section that fully specifies the sibling convention,
  the kinds (good/bad + forward-compatible), multi-technology rules,
  demonstration-only status, and layer-precedence behaviour.
- skills/write.md: update the samples pointer to match.
- README.md: annotate the knowledge tree with the sample sibling shape.
- samples/README.md deleted; content lifted into skills/read.md.
- Both generators (C:\temp\gen_performance_knowledge.py,
  C:\temp\gen_security_knowledge.py) updated to emit at the new paths
  and to stop writing samples/README.md. Re-running them is idempotent
  against the committed layout.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Jesper Schulz-Wedde 2026-04-17 13:45:33 +02:00
parent 0980397d27
commit 62dabf9a11
106 changed files with 89 additions and 98 deletions

View file

@ -0,0 +1,10 @@
tableextension 50118 "Perf Sample SIFTKey" extends "Cust. Ledger Entry"
{
keys
{
key(PerfSampleOpenByCustomer; "Customer No.", Open, "Posting Date")
{
SumIndexFields = "Remaining Amt. (LCY)";
}
}
}

View file

@ -19,7 +19,7 @@ CodeCop rule AA0232 checks that FlowFields backed by CalcSums or aggregation Cal
For each Sum-style FlowField, ensure the source table has a key whose leading fields match the FlowField's CalcFormula WHERE clause and whose SumIndexFields list includes the summed field. Table extensions adding new FlowFields are responsible for adding the supporting key.
See sample: `samples/performance/add-sift-keys-for-flowfields/good.al`.
See sample: `add-sift-keys-for-flowfields.good.al`.
## Anti Pattern

View file

@ -0,0 +1,18 @@
codeunit 50117 "Perf Sample CalcFieldsInLoop Bad"
{
procedure ProcessLargeLines(var SalesHeader: Record "Sales Header"; var SalesLine: Record "Sales Line")
begin
SalesLine.SetRange("Document Type", SalesHeader."Document Type");
SalesLine.SetRange("Document No.", SalesHeader."No.");
if SalesLine.FindSet() then
repeat
SalesHeader.CalcFields(Amount);
if SalesHeader.Amount > 1000 then
ProcessLine(SalesLine);
until SalesLine.Next() = 0;
end;
local procedure ProcessLine(var SalesLine: Record "Sales Line")
begin
end;
}

View file

@ -0,0 +1,18 @@
codeunit 50116 "Perf Sample CalcFieldsInLoop Good"
{
procedure ProcessLargeLines(var SalesHeader: Record "Sales Header"; var SalesLine: Record "Sales Line")
begin
SalesHeader.CalcFields(Amount);
SalesLine.SetRange("Document Type", SalesHeader."Document Type");
SalesLine.SetRange("Document No.", SalesHeader."No.");
if SalesLine.FindSet() then
repeat
if SalesHeader.Amount > 1000 then
ProcessLine(SalesLine);
until SalesLine.Next() = 0;
end;
local procedure ProcessLine(var SalesLine: Record "Sales Line")
begin
end;
}

View file

@ -19,11 +19,11 @@ CalcFields evaluates one or more FlowFields for the current record by issuing a
Move CalcFields out of the iteration. If the total is what you need, use CalcSums on the filtered parent set. If row-by-row FlowField values are needed, reshape the computation so the aggregate runs once — for example by joining against a temporary table populated in a single batched query.
See sample: `samples/performance/avoid-calcfields-in-loops/good.al`.
See sample: `avoid-calcfields-in-loops.good.al`.
## Anti Pattern
Calling CalcFields inside `repeat ... until Next() = 0` on a hot parent record is the textbook N+1 pattern. Even a modest parent set size (hundreds of rows) turns into thousands of round-trips.
See sample: `samples/performance/avoid-calcfields-in-loops/bad.al`.
See sample: `avoid-calcfields-in-loops.bad.al`.

View file

@ -0,0 +1,15 @@
codeunit 50129 "Perf Sample CommitInLoop Bad"
{
procedure ReleaseAllOrders()
var
SalesHeader: Record "Sales Header";
begin
SalesHeader.SetRange(Status, SalesHeader.Status::Open);
if SalesHeader.FindSet() then
repeat
SalesHeader.Status := SalesHeader.Status::Released;
SalesHeader.Modify();
Commit();
until SalesHeader.Next() = 0;
end;
}

View file

@ -23,5 +23,5 @@ If the batch is large enough that a single transaction is untenable, process it
Placing Commit inside `repeat ... until Next() = 0` is almost always a mistake: it is unusual for the correctness of the operation to depend on per-row commits, and the cost of starting a new transaction on every row dominates the work.
See sample: `samples/performance/avoid-commit-inside-loops/bad.al`.
See sample: `avoid-commit-inside-loops.bad.al`.

View file

@ -0,0 +1,14 @@
codeunit 50105 "Perf Sample AvoidFindFirstNext Bad"
{
procedure EmitAllItems(var Item: Record Item)
begin
if Item.FindFirst() then
repeat
EmitItem(Item);
until Item.Next() = 0;
end;
local procedure EmitItem(var Item: Record Item)
begin
end;
}

View file

@ -23,5 +23,5 @@ Choose the Find variant that matches the operation: FindSet for full iteration,
Writing `if Rec.FindFirst() then repeat ... until Rec.Next() = 0` is the canonical AA0233 offender. The loop wastes bandwidth and obscures the author's intent.
See sample: `samples/performance/avoid-findfirst-with-next/bad.al`.
See sample: `avoid-findfirst-with-next.bad.al`.

View file

@ -0,0 +1,11 @@
codeunit 50127 "Perf Sample UserInTxn Bad"
{
procedure ArchiveSalesHeader(var SalesHeader: Record "Sales Header")
begin
SalesHeader.Status := SalesHeader.Status::Released;
SalesHeader.Modify();
if not Confirm('Archive document %1?', false, SalesHeader."No.") then
exit;
SalesHeader.Delete(true);
end;
}

View file

@ -0,0 +1,14 @@
codeunit 50126 "Perf Sample UserInTxn Good"
{
procedure ArchiveSalesHeader(var SalesHeader: Record "Sales Header")
begin
if not Confirm('Archive document %1?', false, SalesHeader."No.") then
exit;
DoArchive(SalesHeader);
end;
local procedure DoArchive(var SalesHeader: Record "Sales Header")
begin
// only Insert/Modify/Delete calls happen here; no prompts
end;
}

View file

@ -19,11 +19,11 @@ Confirm, StrMenu, Message, and any other user-facing dialog pauses execution whi
Gather every user decision before the writing phase begins. Once the decisions are known, run the transaction end-to-end without prompts.
See sample: `samples/performance/avoid-user-interaction-in-transactions/good.al`.
See sample: `avoid-user-interaction-in-transactions.good.al`.
## Anti Pattern
Calling Confirm or StrMenu from inside an OnInsert, OnModify, or OnDelete trigger — or from any code path that has already started modifying records — blocks on user input while holding locks.
See sample: `samples/performance/avoid-user-interaction-in-transactions/bad.al`.
See sample: `avoid-user-interaction-in-transactions.bad.al`.

View file

@ -0,0 +1,16 @@
codeunit 50101 "Perf Sample FilterBeforeFind Bad"
{
procedure ProcessUsCustomers(var Customer: Record Customer)
begin
if Customer.FindSet() then
repeat
if Customer."Country/Region Code" = 'US' then
ProcessCustomer(Customer);
until Customer.Next() = 0;
end;
local procedure ProcessCustomer(var Customer: Record Customer)
begin
// per-customer work
end;
}

View file

@ -0,0 +1,16 @@
codeunit 50100 "Perf Sample FilterBeforeFind Good"
{
procedure ProcessUsCustomers(var Customer: Record Customer)
begin
Customer.SetRange("Country/Region Code", 'US');
if Customer.FindSet() then
repeat
ProcessCustomer(Customer);
until Customer.Next() = 0;
end;
local procedure ProcessCustomer(var Customer: Record Customer)
begin
// per-customer work
end;
}

View file

@ -19,11 +19,11 @@ Every call to FindSet, Find, or FindFirst on an unfiltered record variable scans
Apply SetRange or SetFilter to narrow the record set before calling FindSet or Find. The filters should match a key on the table (see set-current-key-to-match-filters). When iterating rows that belong to a parent record, set all key-field filters before the find call — never inside the repeat loop.
See sample: `samples/performance/filter-before-find/good.al`.
See sample: `filter-before-find.good.al`.
## Anti Pattern
Calling FindSet with no filters and then discarding rows inside the loop with an if-statement forces the platform to read every row of the table before your code even runs.
See sample: `samples/performance/filter-before-find/bad.al`.
See sample: `filter-before-find.bad.al`.

View file

@ -0,0 +1,12 @@
codeunit 50140 "Perf Sample Subscriber Bad"
{
[EventSubscriber(ObjectType::Table, Database::"Sales Line", 'OnAfterValidateEvent', 'No.', false, false)]
local procedure HeavyWorkOnSalesLineNo(var Rec: Record "Sales Line"; var xRec: Record "Sales Line")
var
HttpClient: HttpClient;
HttpResponse: HttpResponseMessage;
begin
// synchronous external call on a hot event
HttpClient.Get('https://example.com/validate?no=' + Rec."No.", HttpResponse);
end;
}

View file

@ -23,5 +23,5 @@ Keep subscribers small: guard early with inexpensive checks, defer heavy work to
Calling an external web service, running a report, or iterating a large table from inside an event subscriber on a hot publisher makes every operation on that publisher as slow as the heaviest subscriber.
See sample: `samples/performance/keep-event-subscribers-lightweight/bad.al`.
See sample: `keep-event-subscribers-lightweight.bad.al`.

View file

@ -0,0 +1,18 @@
codeunit 50128 "Perf Sample TxnScope Bad"
{
procedure ImportCustomers(var Source: List of [Text])
var
Customer: Record Customer;
HttpClient: HttpClient;
HttpResponse: HttpResponseMessage;
Row: Text;
begin
foreach Row in Source do begin
// external call inside the write transaction
HttpClient.Get('https://example.com/validate?row=' + Row, HttpResponse);
Customer.Init();
// ... populate from Row ...
Customer.Insert(true);
end;
end;
}

View file

@ -0,0 +1,22 @@
codeunit 50123 "Perf Sample TxnScope Good"
{
procedure ImportCustomers(var Source: List of [Text])
var
Prepared: Record Customer temporary;
Customer: Record Customer;
begin
// read, validate, and shape outside the transaction
PrepareRows(Source, Prepared);
// transaction starts here: only Insert/Modify calls
if Prepared.FindSet() then
repeat
Customer := Prepared;
Customer.Insert(true);
until Prepared.Next() = 0;
end;
local procedure PrepareRows(var Source: List of [Text]; var Prepared: Record Customer temporary)
begin
end;
}

View file

@ -19,11 +19,11 @@ Every write operation runs inside a transaction that holds locks until the trans
Perform data reads, calculations, and external integrations outside the transaction whenever possible. Enter the writing phase with all inputs computed, execute the minimum set of Insert, Modify, and Delete calls, and exit. If you have a long-running batch, split it into checkpoints at safe boundaries (see avoid-commit-inside-loops).
See sample: `samples/performance/keep-transaction-scope-short/good.al`.
See sample: `keep-transaction-scope-short.good.al`.
## Anti Pattern
Opening a transaction, then performing external web-service calls, heavy report runs, or user-facing dialogs while the locks are held, suspends every other session that needs the same rows for as long as the external operation takes.
See sample: `samples/performance/keep-transaction-scope-short/bad.al`.
See sample: `keep-transaction-scope-short.bad.al`.

View file

@ -0,0 +1,10 @@
codeunit 50107 "Perf Sample OnlyFetchUsed Bad"
{
procedure CustomerHasEntries(CustomerNo: Code[20]): Boolean
var
CustLedgerEntry: Record "Cust. Ledger Entry";
begin
CustLedgerEntry.SetRange("Customer No.", CustomerNo);
exit(CustLedgerEntry.FindSet());
end;
}

View file

@ -0,0 +1,10 @@
codeunit 50106 "Perf Sample OnlyFetchUsed Good"
{
procedure CustomerHasEntries(CustomerNo: Code[20]): Boolean
var
CustLedgerEntry: Record "Cust. Ledger Entry";
begin
CustLedgerEntry.SetRange("Customer No.", CustomerNo);
exit(not CustLedgerEntry.IsEmpty());
end;
}

View file

@ -19,11 +19,11 @@ CodeCop rule AA0175 flags code that retrieves a record and then does not use it.
Retrieve a record only when you need one or more of its field values. When you only need to know whether at least one row matches a filter, use IsEmpty (see use-isempty-for-existence-checks). When you only need a subset of fields, use SetLoadFields (see use-setloadfields-for-partial-records).
See sample: `samples/performance/only-fetch-records-you-use/good.al`.
See sample: `only-fetch-records-you-use.good.al`.
## Anti Pattern
Calling FindSet or Get and then ignoring the result, or using it only as a boolean existence test, performs the full fetch and throws the data away.
See sample: `samples/performance/only-fetch-records-you-use/bad.al`.
See sample: `only-fetch-records-you-use.bad.al`.

View file

@ -0,0 +1,20 @@
codeunit 50135 "Perf Sample RecordRef Bad"
{
procedure BlockCustomer(CustomerNo: Code[20])
var
RecRef: RecordRef;
PkRef: KeyRef;
NoRef: FieldRef;
BlockedRef: FieldRef;
begin
RecRef.Open(Database::Customer);
PkRef := RecRef.KeyIndex(1);
NoRef := PkRef.FieldIndex(1);
NoRef.SetRange(CustomerNo);
if not RecRef.FindFirst() then
exit;
BlockedRef := RecRef.Field(54);
BlockedRef.Value(2);
RecRef.Modify(true);
end;
}

View file

@ -0,0 +1,12 @@
codeunit 50134 "Perf Sample RecordRef Good"
{
procedure BlockCustomer(CustomerNo: Code[20])
var
Customer: Record Customer;
begin
if not Customer.Get(CustomerNo) then
exit;
Customer.Blocked := Customer.Blocked::All;
Customer.Modify(true);
end;
}

View file

@ -19,11 +19,11 @@ RecordRef and FieldRef are the platform's reflection API: they work across table
Use Record variables for code paths that target a known table. Reach for RecordRef and FieldRef only when the table is genuinely dynamic (generic export/import, field-agnostic utilities, cross-table integrations).
See sample: `samples/performance/prefer-direct-record-over-recordref/good.al`.
See sample: `prefer-direct-record-over-recordref.good.al`.
## Anti Pattern
Using RecordRef as a habit, even when the target table is hardcoded two lines earlier, costs performance and hides intent from reviewers.
See sample: `samples/performance/prefer-direct-record-over-recordref/bad.al`.
See sample: `prefer-direct-record-over-recordref.bad.al`.

View file

@ -0,0 +1,11 @@
codeunit 50131 "Perf Sample GetVsFind Bad"
{
procedure CustomerName(CustomerNo: Code[20]): Text[100]
var
Customer: Record Customer;
begin
Customer.SetRange("No.", CustomerNo);
if Customer.FindFirst() then
exit(Customer.Name);
end;
}

View file

@ -0,0 +1,10 @@
codeunit 50130 "Perf Sample GetVsFind Good"
{
procedure CustomerName(CustomerNo: Code[20]): Text[100]
var
Customer: Record Customer;
begin
if Customer.Get(CustomerNo) then
exit(Customer.Name);
end;
}

View file

@ -19,11 +19,11 @@ Get is a direct primary-key lookup: one index seek, one row, done. FindFirst wit
When the complete primary key is known, call Get. Use FindFirst only for non-primary-key lookups or when the filter is a partial prefix of the key.
See sample: `samples/performance/prefer-get-for-primary-key-lookups/good.al`.
See sample: `prefer-get-for-primary-key-lookups.good.al`.
## Anti Pattern
Setting one SetRange per primary-key field and then calling FindFirst reproduces Get with more typing and slightly worse performance.
See sample: `samples/performance/prefer-get-for-primary-key-lookups/bad.al`.
See sample: `prefer-get-for-primary-key-lookups.bad.al`.

View file

@ -0,0 +1,9 @@
codeunit 50122 "Perf Sample SetCurrentKey Good"
{
procedure LinesForDocument(DocumentType: Enum "Sales Document Type"; DocumentNo: Code[20]; var SalesLine: Record "Sales Line")
begin
SalesLine.SetCurrentKey("Document Type", "Document No.", "Line No.");
SalesLine.SetRange("Document Type", DocumentType);
SalesLine.SetRange("Document No.", DocumentNo);
end;
}

View file

@ -19,7 +19,7 @@ AL chooses a key for a Find call based on the current SetCurrentKey selection. W
Call SetCurrentKey with the fields you filter and sort on, in the order they appear in a table key. If no suitable key exists, add one via a table extension rather than relying on an unsupported filter pattern.
See sample: `samples/performance/set-current-key-to-match-filters/good.al`.
See sample: `set-current-key-to-match-filters.good.al`.
## Anti Pattern

View file

@ -0,0 +1,17 @@
report 50112 "Perf Sample AddLoadFields Good"
{
dataset
{
dataitem(Cust; "Cust. Ledger Entry")
{
column(CustomerNo; "Customer No.") { }
column(PostingDate; "Posting Date") { }
column(Amount; Amount) { }
trigger OnPreDataItem()
begin
AddLoadFields("Customer No.", "Posting Date", Amount);
end;
}
}
}

View file

@ -19,7 +19,7 @@ Reports iterate a dataitem's record automatically; the developer does not contro
In each dataitem's OnPreDataItem trigger, call AddLoadFields for every field used by the layout, by the dataitem's triggers, and by any code that runs in the row-level event hooks. If the layout uses a FlowField, also ensure CalcFields is called and that the underlying key is loaded (see add-sift-keys-for-flowfields).
See sample: `samples/performance/use-addloadfields-in-report-layouts/good.al`.
See sample: `use-addloadfields-in-report-layouts.good.al`.
## Anti Pattern

View file

@ -0,0 +1,14 @@
codeunit 50115 "Perf Sample CalcSums Bad"
{
procedure OutstandingForCustomer(CustomerNo: Code[20]) Total: Decimal
var
CustLedgerEntry: Record "Cust. Ledger Entry";
begin
CustLedgerEntry.SetRange("Customer No.", CustomerNo);
CustLedgerEntry.SetRange(Open, true);
if CustLedgerEntry.FindSet() then
repeat
Total += CustLedgerEntry."Remaining Amt. (LCY)";
until CustLedgerEntry.Next() = 0;
end;
}

View file

@ -0,0 +1,12 @@
codeunit 50114 "Perf Sample CalcSums Good"
{
procedure OutstandingForCustomer(CustomerNo: Code[20]): Decimal
var
CustLedgerEntry: Record "Cust. Ledger Entry";
begin
CustLedgerEntry.SetRange("Customer No.", CustomerNo);
CustLedgerEntry.SetRange(Open, true);
CustLedgerEntry.CalcSums("Remaining Amt. (LCY)");
exit(CustLedgerEntry."Remaining Amt. (LCY)");
end;
}

View file

@ -19,11 +19,11 @@ When the task is to compute a sum over a filtered set, CalcSums lets the platfor
Set the required filters on the record, then call CalcSums on the field you want aggregated. Ensure the table has a key whose SumIndexFields includes the summed field and whose key prefix matches the filters (see add-sift-keys-for-flowfields).
See sample: `samples/performance/use-calcsums-for-flowfield-totals/good.al`.
See sample: `use-calcsums-for-flowfield-totals.good.al`.
## Anti Pattern
Looping a filtered set with FindSet and adding a field to an accumulator on every iteration performs work in AL that SQL already knows how to do in one aggregate query.
See sample: `samples/performance/use-calcsums-for-flowfield-totals/bad.al`.
See sample: `use-calcsums-for-flowfield-totals.bad.al`.

View file

@ -0,0 +1,10 @@
codeunit 50109 "Perf Sample FindSetReadonly Bad"
{
procedure SumInvoiceLines(var SalesLine: Record "Sales Line") Total: Decimal
begin
if SalesLine.FindSet(true) then
repeat
Total += SalesLine."Line Amount";
until SalesLine.Next() = 0;
end;
}

View file

@ -0,0 +1,10 @@
codeunit 50108 "Perf Sample FindSetReadonly Good"
{
procedure SumInvoiceLines(var SalesLine: Record "Sales Line") Total: Decimal
begin
if SalesLine.FindSet() then
repeat
Total += SalesLine."Line Amount";
until SalesLine.Next() = 0;
end;
}

View file

@ -19,11 +19,11 @@ FindSet has two modes: FindSet() and FindSet(false) are read-only and take no wr
Call FindSet with no arguments when the loop only reads field values. Pass `true` only when the same loop is expected to call Modify, Delete, or Rename on the record, and the correctness of the operation depends on the table being locked for the full iteration.
See sample: `samples/performance/use-findset-readonly-by-default/good.al`.
See sample: `use-findset-readonly-by-default.good.al`.
## Anti Pattern
Writing FindSet(true) reflexively for every iteration forces the platform to take a LockTable on every call, even when the loop only reads values. The older two-parameter signature `FindSet(ForUpdate, UpdateKey)` is obsolete and must not be used.
See sample: `samples/performance/use-findset-readonly-by-default/bad.al`.
See sample: `use-findset-readonly-by-default.bad.al`.

View file

@ -0,0 +1,10 @@
codeunit 50103 "Perf Sample FindSetWithNext Bad"
{
procedure SumLineAmounts(var SalesLine: Record "Sales Line") Total: Decimal
begin
if SalesLine.FindFirst() then
repeat
Total += SalesLine."Line Amount";
until SalesLine.Next() = 0;
end;
}

View file

@ -0,0 +1,10 @@
codeunit 50102 "Perf Sample FindSetWithNext Good"
{
procedure SumLineAmounts(var SalesLine: Record "Sales Line") Total: Decimal
begin
if SalesLine.FindSet() then
repeat
Total += SalesLine."Line Amount";
until SalesLine.Next() = 0;
end;
}

View file

@ -19,11 +19,11 @@ When iterating over a filtered set of records with repeat-until, use FindSet tog
Call FindSet to start the iteration and Next to advance. Guard the loop with the standard `if FindSet() then ... until Next() = 0` idiom so callers can still handle the empty-set case.
See sample: `samples/performance/use-findset-with-next/good.al`.
See sample: `use-findset-with-next.good.al`.
## Anti Pattern
Starting a repeat-until loop with FindFirst or FindLast reads only one row and then calls Next on an iterator that was not intended for full-set traversal. The platform pays extra work to fetch the single row and the loop silhouette is misleading to reviewers.
See sample: `samples/performance/use-findset-with-next/bad.al`.
See sample: `use-findset-with-next.bad.al`.

View file

@ -0,0 +1,12 @@
codeunit 50132 "Perf Sample InsertParam Good"
{
procedure BulkLoadTempItems(var TempItem: Record Item temporary; Source: List of [Code[20]])
var
ItemNo: Code[20];
begin
foreach ItemNo in Source do begin
TempItem."No." := ItemNo;
TempItem.Insert(false);
end;
end;
}

View file

@ -19,7 +19,7 @@ Insert, Modify, and Delete accept a boolean that controls whether the table's On
Call Insert(true), Modify(true), or Delete(true) when the table's trigger logic is part of the operation's semantics. Call Insert(false), Modify(false), or Delete(false) when the operation is bulk data movement or temporary-table manipulation and the trigger would duplicate work or fire invalid side effects.
See sample: `samples/performance/use-insert-false-when-skipping-triggers/good.al`.
See sample: `use-insert-false-when-skipping-triggers.good.al`.
## Anti Pattern

View file

@ -0,0 +1,11 @@
codeunit 50121 "Perf Sample IsEmpty Bad"
{
procedure HasOpenDocuments(CustomerNo: Code[20]): Boolean
var
SalesHeader: Record "Sales Header";
begin
SalesHeader.SetRange("Sell-to Customer No.", CustomerNo);
SalesHeader.SetRange(Status, SalesHeader.Status::Open);
exit(SalesHeader.Count() > 0);
end;
}

View file

@ -0,0 +1,11 @@
codeunit 50120 "Perf Sample IsEmpty Good"
{
procedure HasOpenDocuments(CustomerNo: Code[20]): Boolean
var
SalesHeader: Record "Sales Header";
begin
SalesHeader.SetRange("Sell-to Customer No.", CustomerNo);
SalesHeader.SetRange(Status, SalesHeader.Status::Open);
exit(not SalesHeader.IsEmpty());
end;
}

View file

@ -19,11 +19,11 @@ IsEmpty is the cheapest way to answer whether at least one row matches the curre
Use `if not Rec.IsEmpty() then ...` for existence checks. Reserve Count for cases where the exact number of rows is needed, and FindFirst for cases where you actually want the row's field values.
See sample: `samples/performance/use-isempty-for-existence-checks/good.al`.
See sample: `use-isempty-for-existence-checks.good.al`.
## Anti Pattern
`if Rec.Count() > 0` iterates the whole set just to answer a yes/no question. `if Rec.FindFirst() then` loads an entire row of data the caller never reads.
See sample: `samples/performance/use-isempty-for-existence-checks/bad.al`.
See sample: `use-isempty-for-existence-checks.bad.al`.

View file

@ -0,0 +1,14 @@
codeunit 50111 "Perf Sample SetLoadFields Bad"
{
procedure ExportItemNumbers(var Item: Record Item)
begin
if Item.FindSet() then
repeat
Export(Item."No.", Item.Description);
until Item.Next() = 0;
end;
local procedure Export(ItemNo: Code[20]; Description: Text[100])
begin
end;
}

View file

@ -0,0 +1,15 @@
codeunit 50110 "Perf Sample SetLoadFields Good"
{
procedure ExportItemNumbers(var Item: Record Item)
begin
Item.SetLoadFields("No.", Description);
if Item.FindSet() then
repeat
Export(Item."No.", Item.Description);
until Item.Next() = 0;
end;
local procedure Export(ItemNo: Code[20]; Description: Text[100])
begin
end;
}

View file

@ -19,11 +19,11 @@ SetLoadFields instructs the platform to hydrate only the listed fields on a reco
Call SetLoadFields before FindSet, FindFirst, or Get whenever the code path only reads a subset of fields. List every field that is read during the operation, including fields used in filters, calculations, and downstream function calls. Omitting a field that is later accessed triggers a second round-trip.
See sample: `samples/performance/use-setloadfields-for-partial-records/good.al`.
See sample: `use-setloadfields-for-partial-records.good.al`.
## Anti Pattern
Iterating a large set and reading only two or three fields without SetLoadFields forces the platform to transport every column for every row, including BLOBs and unused text fields.
See sample: `samples/performance/use-setloadfields-for-partial-records/bad.al`.
See sample: `use-setloadfields-for-partial-records.bad.al`.

View file

@ -0,0 +1,17 @@
codeunit 50138 "Perf Sample SingleInstance Good"
{
SingleInstance = true;
var
Cached: Record "Sales & Receivables Setup";
Loaded: Boolean;
procedure GetSetup(): Record "Sales & Receivables Setup"
begin
if not Loaded then begin
Cached.Get();
Loaded := true;
end;
exit(Cached);
end;
}

View file

@ -19,7 +19,7 @@ A SingleInstance codeunit lives once per session. Variables on it survive across
Store long-lived, read-often, rarely-changing data on a SingleInstance codeunit, populated lazily on first access. Keep the cached footprint small: a handful of booleans, a setup record, a few derived values. Be explicit about invalidation if the source can change during the session.
See sample: `samples/performance/use-single-instance-codeunits-for-caching/good.al`.
See sample: `use-single-instance-codeunits-for-caching.good.al`.
## Anti Pattern

View file

@ -0,0 +1,7 @@
codeunit 50137 "Perf Sample StrSubstNo Bad"
{
procedure CustomerGreeting(var Customer: Record Customer): Text
begin
exit('Hello, ' + Customer.Name + ' (' + Customer."No." + ')');
end;
}

View file

@ -0,0 +1,9 @@
codeunit 50136 "Perf Sample StrSubstNo Good"
{
procedure CustomerGreeting(var Customer: Record Customer): Text
var
GreetingLbl: Label 'Hello, %1 (%2)';
begin
exit(StrSubstNo(GreetingLbl, Customer.Name, Customer."No."));
end;
}

View file

@ -19,11 +19,11 @@ StrSubstNo formats values into a placeholder template in a single call. Manual c
Declare the template as a Label (so it can be localized) and format with StrSubstNo. Pass values in the order the placeholders expect; StrSubstNo handles locale-sensitive conversions consistently.
See sample: `samples/performance/use-strsubstno-for-message-formatting/good.al`.
See sample: `use-strsubstno-for-message-formatting.good.al`.
## Anti Pattern
Building a user-facing string by concatenating record field values with string literals ignores locale rules and allocates more than necessary.
See sample: `samples/performance/use-strsubstno-for-message-formatting/bad.al`.
See sample: `use-strsubstno-for-message-formatting.bad.al`.

View file

@ -0,0 +1,16 @@
codeunit 50124 "Perf Sample TempTable Good"
{
procedure BuildAffectedItems(var TempItem: Record Item temporary)
var
SalesLine: Record "Sales Line";
begin
TempItem.Reset();
TempItem.DeleteAll();
SalesLine.SetRange(Type, SalesLine.Type::Item);
if SalesLine.FindSet() then
repeat
TempItem."No." := SalesLine."No.";
if TempItem.Insert(false) then;
until SalesLine.Next() = 0;
end;
}

View file

@ -19,7 +19,7 @@ Temporary tables live in memory, not in SQL. They are the correct primary data s
Declare the record variable with `temporary` when the data is scratch. Populate it with Insert(false) to avoid firing triggers. Clear the table explicitly with DeleteAll when the variable's scope is long-lived (a SingleInstance codeunit or a reused session variable) and needs to be reset between uses.
See sample: `samples/performance/use-temporary-tables-for-intermediate-data/good.al`.
See sample: `use-temporary-tables-for-intermediate-data.good.al`.
## Anti Pattern

View file

@ -0,0 +1,14 @@
codeunit 50225 "Sec Sample ErrorDisclosure Bad"
{
procedure Connect()
begin
if not TryConnect() then
Error('Failed to connect to Server=PROD-SQL01;Database=NAV;User=svc_admin: %1', GetLastErrorText());
end;
[TryFunction]
local procedure TryConnect()
begin
// ...
end;
}

View file

@ -0,0 +1,24 @@
codeunit 50224 "Sec Sample ErrorDisclosure Good"
{
var
ConnectionFailedErr: Label 'Connection to the external service failed. Contact your administrator.';
procedure Connect()
begin
if not TryConnect() then begin
LogConnectionFailure(GetLastErrorText());
Error(ConnectionFailedErr);
end;
end;
[TryFunction]
local procedure TryConnect()
begin
// ...
end;
local procedure LogConnectionFailure(Detail: Text)
begin
// Route to controlled logging (Session.LogMessage, activity log, etc.).
end;
}

View file

@ -19,11 +19,11 @@ Errors surfaced to end users are routinely forwarded to support systems, capture
Raise end-user errors using localized Labels that describe the condition without naming infrastructure. Emit the actual detail (exception text, endpoint, correlation id) through the application's internal logging channel, where audience and retention are controlled.
See sample: `samples/security/avoid-sensitive-data-in-error-messages/good.al`.
See sample: `avoid-sensitive-data-in-error-messages.good.al`.
## Anti Pattern
Error('Failed to connect to Server=PROD-SQL01;Database=NAV;User=admin: %1', Ex.Message); — every support ticket now carries the server name, database name, and service account.
See sample: `samples/security/avoid-sensitive-data-in-error-messages/bad.al`.
See sample: `avoid-sensitive-data-in-error-messages.bad.al`.

View file

@ -0,0 +1,9 @@
codeunit 50215 "Sec Sample SecretCompose Bad"
{
procedure BuildAuthHeader(Token: Text) AuthHeader: Text
begin
// Token is Text, so the combined value is plaintext.
// The whole shape should have used SecretText + SecretStrSubstNo.
AuthHeader := StrSubstNo('Bearer %1', Token);
end;
}

View file

@ -0,0 +1,7 @@
codeunit 50214 "Sec Sample SecretCompose Good"
{
procedure BuildAuthHeader(Token: SecretText) AuthHeader: SecretText
begin
AuthHeader := SecretStrSubstNo('Bearer %1', Token);
end;
}

View file

@ -19,11 +19,11 @@ SecretStrSubstNo is the SecretText analogue of StrSubstNo. The template is a reg
Format SecretText templates with SecretStrSubstNo. This is the correct primitive for building authorization headers, secret URIs, and any other formatted string that embeds a SecretText. Provide the static parts of the template as a regular string literal; only the substitutions carry the secret value.
See sample: `samples/security/compose-secrets-with-secretstrsubstno/good.al`.
See sample: `compose-secrets-with-secretstrsubstno.good.al`.
## Anti Pattern
Using StrSubstNo (or plain string concatenation) on a plain-Text token to build an authorization header. The result is a Text containing the secret in plaintext, visible in the debugger, inspectable in snapshot debug sessions, and captured by any logging the caller does not control. SecretText should have been used end-to-end.
See sample: `samples/security/compose-secrets-with-secretstrsubstno/bad.al`.
See sample: `compose-secrets-with-secretstrsubstno.bad.al`.

View file

@ -0,0 +1,19 @@
codeunit 50229 "Sec Sample EventPublisher Bad"
{
[IntegrationEvent(false, false)]
local procedure OnBeforeExportCustomer(CustomerNo: Code[20]; ExportCredentials: SecretText; var AllowExport: Boolean)
begin
end;
procedure ExportCustomer(CustomerNo: Code[20]; Credentials: SecretText)
var
AllowExport: Boolean;
begin
// Any subscriber on the tenant receives the credentials and
// can flip AllowExport := true to bypass the publisher's check.
OnBeforeExportCustomer(CustomerNo, Credentials, AllowExport);
if not AllowExport then
exit;
// ... perform export
end;
}

View file

@ -0,0 +1,23 @@
codeunit 50228 "Sec Sample EventPublisher Good"
{
[IntegrationEvent(false, false)]
local procedure OnBeforeExportCustomer(CustomerNo: Code[20])
begin
end;
procedure ExportCustomer(CustomerNo: Code[20])
begin
if not CallerIsAuthorizedToExport(CustomerNo) then
Error('You are not authorized to export this customer.');
OnBeforeExportCustomer(CustomerNo);
// ... perform export using credentials owned by this codeunit
end;
local procedure CallerIsAuthorizedToExport(CustomerNo: Code[20]): Boolean
begin
// Authorization decision stays inside the publisher. Subscribers
// receive only the customer number and cannot influence the
// decision.
end;
}

View file

@ -19,11 +19,11 @@ Events in AL are extensibility contracts. Every subscriber — third-party, inte
Design event signatures to carry only the data a subscriber legitimately needs. Do not pass SecretText, credential material, or flags the publisher depends on for access control. If a subscriber needs to veto an action, model it as a separate OnBefore event whose Handled pattern is documented — not as a general-purpose var Boolean callers can flip.
See sample: `samples/security/do-not-expose-sensitive-data-in-event-publishers/good.al`.
See sample: `do-not-expose-sensitive-data-in-event-publishers.good.al`.
## Anti Pattern
An OnBeforeElevateAccess publisher that exposes `var CanAccess: Boolean` — any subscriber installed on the tenant can flip it to true and escalate. Or a publisher that passes a SecretText parameter it obtained internally, handing it to every subscriber.
See sample: `samples/security/do-not-expose-sensitive-data-in-event-publishers/bad.al`.
See sample: `do-not-expose-sensitive-data-in-event-publishers.bad.al`.

View file

@ -0,0 +1,10 @@
codeunit 50223 "Sec Sample UrlCreds Bad"
{
procedure Call(ApiKey: Text)
var
Client: HttpClient;
Response: HttpResponseMessage;
begin
Client.Get('https://api.example.com/v1/items?api_key=' + ApiKey, Response);
end;
}

View file

@ -0,0 +1,13 @@
codeunit 50222 "Sec Sample UrlCreds Good"
{
procedure Call(ApiKey: SecretText)
var
Client: HttpClient;
Response: HttpResponseMessage;
AuthHeader: SecretText;
begin
AuthHeader := SecretStrSubstNo('Bearer %1', ApiKey);
Client.DefaultRequestHeaders.Add('Authorization', AuthHeader);
Client.Get('https://api.example.com/v1/items', Response);
end;
}

View file

@ -19,11 +19,11 @@ URL query strings and path segments are routinely captured in web-server access
Transport credentials in Authorization headers, carried as SecretText end-to-end (see use-secrettext-with-httpclient). Where the URI itself must carry a secret (for example, a pre-signed URL), build it with SecretStrSubstNo and pass it via SetSecretRequestUri so it is never materialized as Text.
See sample: `samples/security/do-not-put-credentials-in-urls/good.al`.
See sample: `do-not-put-credentials-in-urls.good.al`.
## Anti Pattern
Appending '?api_key=' + Key to a request URL, or embedding a token in a path segment, then calling HttpClient.Get with the resulting Text URL.
See sample: `samples/security/do-not-put-credentials-in-urls/bad.al`.
See sample: `do-not-put-credentials-in-urls.bad.al`.

View file

@ -0,0 +1,15 @@
codeunit 50227 "Sec Sample SwallowErr Bad"
{
procedure Authenticate(): Boolean
begin
if not TryAuthenticate() then
exit(false);
exit(true);
end;
[TryFunction]
local procedure TryAuthenticate()
begin
// ...
end;
}

View file

@ -0,0 +1,24 @@
codeunit 50226 "Sec Sample SwallowErr Good"
{
procedure Authenticate(): Boolean
begin
if TryAuthenticate() then
exit(true);
LogAuthFailure(GetLastErrorText());
exit(false);
end;
[TryFunction]
local procedure TryAuthenticate()
begin
// ...
end;
local procedure LogAuthFailure(Detail: Text)
begin
Session.LogMessage('SEC0001', 'Authentication failed', Verbosity::Warning,
DataClassification::SystemMetadata, TelemetryScope::ExtensionPublisher,
'Detail', Detail);
end;
}

View file

@ -19,11 +19,11 @@ Authentication failures, permission denials, and unexpected error paths in secur
Use TryFunctions to contain errors around security-relevant work, but always log the failure (category, GetLastErrorText, and enough context to identify the operation) before deciding whether to surface a user-facing error. Never discard a caught security error without a trace.
See sample: `samples/security/do-not-swallow-security-errors-silently/good.al`.
See sample: `do-not-swallow-security-errors-silently.good.al`.
## Anti Pattern
`if not TryAuthenticate() then exit;` with no logging and no user-facing error. An authentication-bypass attempt, a revoked credential, and a transient network glitch are now indistinguishable.
See sample: `samples/security/do-not-swallow-security-errors-silently/bad.al`.
See sample: `do-not-swallow-security-errors-silently.bad.al`.

View file

@ -0,0 +1,6 @@
permissionset 50201 "Sec Sample Full Access"
{
Assignable = true;
Caption = 'Full Access (sample anti-pattern)';
Permissions = tabledata * = RIMD;
}

View file

@ -0,0 +1,9 @@
permissionset 50200 "Sec Sample Sales Order Entry"
{
Assignable = true;
Caption = 'Sales Order Entry (sample)';
Permissions =
tabledata "Sales Header" = RIM,
tabledata "Sales Line" = RIMD,
tabledata Customer = R;
}

View file

@ -19,11 +19,11 @@ Permission sets define the tabledata and object rights granted to every user or
Enumerate the specific tabledata objects a role needs and grant only the letters (R, I, M, D) that role genuinely uses. A sales order-entry role typically needs RIM on Sales Header, RIMD on Sales Line, and R on Customer — not blanket RIMD. Permission sets SHOULD be granular and role-shaped; a single permission set that covers every role in an extension is a design smell.
See sample: `samples/security/follow-least-privilege-in-permission-sets/good.al`.
See sample: `follow-least-privilege-in-permission-sets.good.al`.
## Anti Pattern
Granting `tabledata * = RIMD` (or any wildcard with I, M, or D) in a permission set. This bypasses any meaningful separation of duties the extension could enforce and gives unreviewed code paths the ability to insert, modify, and delete on any table.
See sample: `samples/security/follow-least-privilege-in-permission-sets/bad.al`.
See sample: `follow-least-privilege-in-permission-sets.bad.al`.

View file

@ -0,0 +1,10 @@
codeunit 50207 "Sec Sample HardcodedSecret Bad"
{
var
HardcodedApiKeyLbl: Label 'sk-live-1234567890abcdef', Locked = true;
procedure GetApiKey(): Text
begin
exit(HardcodedApiKeyLbl);
end;
}

View file

@ -0,0 +1,12 @@
codeunit 50206 "Sec Sample HardcodedSecret Good"
{
procedure GetApiKey() ApiKey: SecretText
var
StoredValue: SecretText;
begin
if IsolatedStorage.Contains('ApiKey', DataScope::Module) then
if IsolatedStorage.Get('ApiKey', DataScope::Module, StoredValue) then
exit(StoredValue);
Error('API key is not configured.');
end;
}

View file

@ -19,11 +19,11 @@ A secret embedded in AL source — API key, password, connection string, token
Retrieve secrets at runtime from a protected store: Azure Key Vault for production workloads (see prefer-azure-key-vault-for-production-secrets) or IsolatedStorage for tenant-local encrypted values (see use-isolated-storage-for-module-and-company-secrets). Carry the retrieved value in a SecretText variable end-to-end (see use-secrettext-for-credentials).
See sample: `samples/security/never-hardcode-secrets-in-al/good.al`.
See sample: `never-hardcode-secrets-in-al.good.al`.
## Anti Pattern
Assigning a secret literal to a Text, Code, or Label variable (including labels marked as constants). The secret is now part of the compiled app and indistinguishable from non-sensitive content to callers and tools.
See sample: `samples/security/never-hardcode-secrets-in-al/bad.al`.
See sample: `never-hardcode-secrets-in-al.bad.al`.

View file

@ -0,0 +1,10 @@
codeunit 50219 "Sec Sample Https Bad"
{
procedure CallExternal()
var
Client: HttpClient;
Response: HttpResponseMessage;
begin
Client.Get('http://api.example.com/data', Response);
end;
}

View file

@ -0,0 +1,12 @@
codeunit 50218 "Sec Sample Https Good"
{
procedure CallExternal(Endpoint: Text)
var
Client: HttpClient;
Response: HttpResponseMessage;
begin
if not Endpoint.StartsWith('https://') then
Error('Only HTTPS endpoints are allowed.');
Client.Get(Endpoint, Response);
end;
}

View file

@ -19,11 +19,11 @@ HttpClient can issue requests over plaintext HTTP as easily as over HTTPS. A req
Call external services exclusively over https://. When the destination is configurable, validate at runtime that the scheme is https before issuing the request, and fail closed with a clear (non-disclosing) error otherwise.
See sample: `samples/security/require-https-for-external-calls/good.al`.
See sample: `require-https-for-external-calls.good.al`.
## Anti Pattern
Issuing HttpClient.Get('http://...'), or accepting an arbitrary user-supplied URL and passing it straight to HttpClient without scheme validation.
See sample: `samples/security/require-https-for-external-calls/bad.al`.
See sample: `require-https-for-external-calls.bad.al`.

View file

@ -0,0 +1,11 @@
codeunit 50221 "Sec Sample Timeout Bad"
{
procedure CallExternal()
var
Client: HttpClient;
Response: HttpResponseMessage;
begin
// No Timeout set; a hung endpoint stalls the caller.
Client.Get('https://api.example.com/data', Response);
end;
}

View file

@ -0,0 +1,12 @@
codeunit 50220 "Sec Sample Timeout Good"
{
procedure CallExternal()
var
Client: HttpClient;
Response: HttpResponseMessage;
begin
Client.Timeout := 10000; // 10 seconds
if not Client.Get('https://api.example.com/data', Response) then
Error('External service is unavailable.');
end;
}

View file

@ -19,11 +19,11 @@ An HttpClient with no explicit timeout relies on defaults that may be long enoug
Set HttpClient.Timeout to a bounded value (seconds, not minutes) that reflects the SLA of the dependency. Handle the timeout error without leaking endpoint details to end users (see avoid-sensitive-data-in-error-messages).
See sample: `samples/security/set-timeouts-for-external-calls/good.al`.
See sample: `set-timeouts-for-external-calls.good.al`.
## Anti Pattern
Issuing HttpClient requests without setting Timeout and without a timeout-handling branch. A slow dependency now has an unbounded blast radius inside the extension.
See sample: `samples/security/set-timeouts-for-external-calls/bad.al`.
See sample: `set-timeouts-for-external-calls.bad.al`.

View file

@ -0,0 +1,7 @@
permissionset 50203 "Sec Sample Direct Write"
{
Assignable = true;
Caption = 'Direct write granted to every caller (sample anti-pattern)';
Permissions =
tabledata "Sales Header" = RM;
}

View file

@ -0,0 +1,34 @@
permissionset 50202 "Sec Sample Elevated Write"
{
Assignable = false;
Caption = 'Elevated write via helper (sample)';
// Callers hold R directly; the helper codeunit assumes this set and
// performs the Modify via indirect permission.
Permissions =
tabledata "Sales Header" = Rmi;
}
codeunit 50231 "Sec Sample Elevated Helper"
{
Access = Public;
Permissions = tabledata "Sales Header" = Rmi;
procedure SetExternalDocumentNo(SalesDocType: Enum "Sales Document Type"; SalesDocNo: Code[20]; NewExternalDocNo: Code[35])
var
SalesHeader: Record "Sales Header";
begin
ValidateCaller();
if NewExternalDocNo = '' then
Error('External document number must be provided.');
if not SalesHeader.Get(SalesDocType, SalesDocNo) then
Error('Sales document not found.');
SalesHeader."External Document No." := NewExternalDocNo;
SalesHeader.Modify(true);
end;
local procedure ValidateCaller()
begin
// Verify the caller is permitted to perform this elevated write
// (role check, setup flag, approvals, etc.).
end;
}

View file

@ -19,11 +19,11 @@ Indirect permissions (ri, ii, mi, di) let a procedure perform an operation again
Where a module exposes a controlled write or delete against a sensitive table, grant the codeunit (or the helper permission set it assumes) the indirect permission (mi, di) it requires, keep direct permissions minimal, and document why the elevation is justified. The helper MUST validate its inputs and the caller's identity before performing the elevated work.
See sample: `samples/security/use-indirect-permissions-for-elevated-access/good.al`.
See sample: `use-indirect-permissions-for-elevated-access.good.al`.
## Anti Pattern
Granting direct M or D on a sensitive tabledata to every role that might invoke a helper, because authoring an indirect-permission codeunit was inconvenient. Every caller now has the elevated right for every code path, not just the one the helper implements.
See sample: `samples/security/use-indirect-permissions-for-elevated-access/bad.al`.
See sample: `use-indirect-permissions-for-elevated-access.bad.al`.

View file

@ -0,0 +1,13 @@
codeunit 50205 "Sec Sample Inherent Bad"
{
// No InherentPermissions attribute: every caller must hold
// tabledata "Sec Sample Lookup" = R just to look up a name.
procedure GetLookupName(LookupCode: Code[20]): Text[100]
var
Lookup: Record "Sec Sample Lookup";
begin
if Lookup.Get(LookupCode) then
exit(Lookup.Name);
exit('');
end;
}

View file

@ -0,0 +1,28 @@
table 50230 "Sec Sample Lookup"
{
DataClassification = SystemMetadata;
fields
{
field(1; "Code"; Code[20]) { }
field(2; "Name"; Text[100]) { }
}
keys
{
key(PK; "Code") { Clustered = true; }
}
}
codeunit 50204 "Sec Sample Inherent Good"
{
[InherentPermissions(PermissionObjectType::TableData, Database::"Sec Sample Lookup", 'r')]
procedure GetLookupName(LookupCode: Code[20]): Text[100]
var
Lookup: Record "Sec Sample Lookup";
begin
if Lookup.Get(LookupCode) then
exit(Lookup.Name);
exit('');
end;
}

View file

@ -19,11 +19,11 @@ The InherentPermissions attribute attaches a minimum access grant to a procedure
Annotate read-only helper procedures with InherentPermissions specifying only the tables and access letters the body uses (typically 'r'). Callers do not need direct read rights on the underlying extension-owned table, so the calling role can be narrower. This is the narrowest of the elevation options and is appropriate for read-only lookup helpers.
See sample: `samples/security/use-inherent-permissions-to-grant-minimal-access/good.al`.
See sample: `use-inherent-permissions-to-grant-minimal-access.good.al`.
## Anti Pattern
A helper that reads a single lookup value but forces every calling role to hold tabledata read rights, because the helper does not declare its own inherent permissions. The broad read right then applies to every other code path that role can reach, not just the helper.
See sample: `samples/security/use-inherent-permissions-to-grant-minimal-access/bad.al`.
See sample: `use-inherent-permissions-to-grant-minimal-access.bad.al`.

View file

@ -0,0 +1,17 @@
codeunit 50209 "Sec Sample IsolatedStorage Bad"
{
procedure StoreApiKey(NewKey: Text)
begin
// Plaintext write to IsolatedStorage is not encrypted at rest.
IsolatedStorage.Set('ApiKey', NewKey, DataScope::Module);
end;
procedure GetApiKey(): Text
var
ApiKey: Text;
begin
if IsolatedStorage.Get('ApiKey', DataScope::Module, ApiKey) then
exit(ApiKey);
exit('');
end;
}

View file

@ -0,0 +1,14 @@
codeunit 50208 "Sec Sample IsolatedStorage Good"
{
procedure StoreApiKey(NewKey: SecretText)
begin
IsolatedStorage.SetEncrypted('ApiKey', NewKey, DataScope::Module);
end;
procedure TryGetApiKey(var ApiKey: SecretText): Boolean
begin
if IsolatedStorage.Contains('ApiKey', DataScope::Module) then
exit(IsolatedStorage.Get('ApiKey', DataScope::Module, ApiKey));
exit(false);
end;
}

View file

@ -19,11 +19,11 @@ IsolatedStorage is a per-extension, per-tenant key-value store. DataScope::Modul
Use IsolatedStorage.SetEncrypted to write secrets, IsolatedStorage.Contains to probe, and IsolatedStorage.Get into a SecretText destination to read. Choose DataScope::Company for per-company credentials (for example, a tenant-per-company service account) and DataScope::Module for extension-wide configuration.
See sample: `samples/security/use-isolated-storage-for-module-and-company-secrets/good.al`.
See sample: `use-isolated-storage-for-module-and-company-secrets.good.al`.
## Anti Pattern
Storing secrets in a Setup table column as plain Text, or using IsolatedStorage.Set (unencrypted) for values that authenticate the extension to an external service. Both shapes leave the secret readable by anyone with read rights on the underlying storage.
See sample: `samples/security/use-isolated-storage-for-module-and-company-secrets/bad.al`.
See sample: `use-isolated-storage-for-module-and-company-secrets.bad.al`.

View file

@ -0,0 +1,16 @@
codeunit 50217 "Sec Sample NonDebuggable Bad"
{
// Missing [NonDebuggable]: ResponseText and the extracted token are
// inspectable in the debugger and in snapshot debug sessions.
procedure ParseSessionToken(Response: HttpResponseMessage; var SessionToken: SecretText)
var
ResponseText: Text;
JObject: JsonObject;
JToken: JsonToken;
begin
Response.Content.ReadAs(ResponseText);
JObject.ReadFrom(ResponseText);
JObject.Get('access_token', JToken);
SessionToken := JToken.AsValue().AsText();
end;
}

View file

@ -0,0 +1,15 @@
codeunit 50216 "Sec Sample NonDebuggable Good"
{
[NonDebuggable]
procedure ParseSessionToken(Response: HttpResponseMessage; var SessionToken: SecretText)
var
ResponseText: Text;
JObject: JsonObject;
JToken: JsonToken;
begin
Response.Content.ReadAs(ResponseText);
JObject.ReadFrom(ResponseText);
JObject.Get('access_token', JToken);
SessionToken := JToken.AsValue().AsText();
end;
}

View file

@ -19,11 +19,11 @@ SecretText transit (assignment between SecretText variables, parameters, and ret
Apply [NonDebuggable] to any procedure that reads a response body, parses it, and assigns the extracted secret to a SecretText out-parameter or return. Keep the procedure narrow: it SHOULD do the minimum work required to obtain the SecretText, and nothing else.
See sample: `samples/security/use-nondebuggable-when-parsing-secrets/good.al`.
See sample: `use-nondebuggable-when-parsing-secrets.good.al`.
## Anti Pattern
Parsing a token response in a normal (debuggable) procedure. The plaintext token is visible in debug sessions and snapshots taken during the parse.
See sample: `samples/security/use-nondebuggable-when-parsing-secrets/bad.al`.
See sample: `use-nondebuggable-when-parsing-secrets.bad.al`.

View file

@ -0,0 +1,13 @@
codeunit 50211 "Sec Sample SecretText Bad"
{
procedure SendAuthenticatedRequest(BearerToken: Text)
var
Client: HttpClient;
Response: HttpResponseMessage;
AuthValue: Text;
begin
AuthValue := 'Bearer ' + BearerToken;
Client.DefaultRequestHeaders.Add('Authorization', AuthValue);
Client.Get('https://api.example.com/data', Response);
end;
}

View file

@ -0,0 +1,14 @@
codeunit 50210 "Sec Sample SecretText Good"
{
procedure SendAuthenticatedRequest(BearerToken: SecretText)
var
Client: HttpClient;
Headers: HttpHeaders;
Response: HttpResponseMessage;
AuthValue: SecretText;
begin
AuthValue := SecretStrSubstNo('Bearer %1', BearerToken);
Client.DefaultRequestHeaders.Add('Authorization', AuthValue);
Client.Get('https://api.example.com/data', Response);
end;
}

View file

@ -19,11 +19,11 @@ SecretText is a compile-time-checked AL type for credentials, API keys, tokens,
Type every credential-carrying variable, procedure parameter, and return as SecretText. Compose values with SecretStrSubstNo (see compose-secrets-with-secretstrsubstno). For HttpClient integration, see use-secrettext-with-httpclient. When a secret must be extracted from a Text source, contain that conversion in a NonDebuggable procedure (see use-nondebuggable-when-parsing-secrets).
See sample: `samples/security/use-secrettext-for-credentials/good.al`.
See sample: `use-secrettext-for-credentials.good.al`.
## Anti Pattern
Passing credentials around as Text or Code parameters. Every such variable is visible in the debugger and may be captured by error handlers, logs, and telemetry that treat Text as non-sensitive.
See sample: `samples/security/use-secrettext-for-credentials/bad.al`.
See sample: `use-secrettext-for-credentials.bad.al`.

View file

@ -0,0 +1,12 @@
codeunit 50213 "Sec Sample SecretHttpClient Bad"
{
procedure Call(ApiKey: Text)
var
Client: HttpClient;
Response: HttpResponseMessage;
FullUrl: Text;
begin
FullUrl := 'https://api.example.com/v1?key=' + ApiKey;
Client.Get(FullUrl, Response);
end;
}

Some files were not shown because too many files have changed in this diff Show more