Asset Reconciliation Developer Guide - edmozley/freeitsm GitHub Wiki

Asset reconciliation โ€” Developer Guide

Since 3.1.0 ยท Built by Sandy (@srinivasansanthosh) in PR #164, merged with the changes in the review ยท User side: Assets โ†’ Help โ†’ Discovery & reconciliation

How FreeITSM decides whether a device reported by the inventory agent or Intune is an asset it already has. Before 3.1.0 every source matched on hostname alone, so a renamed computer arrived as a second asset with none of its history. Now a device is matched by what it is (its serial number) before what it is called.


1. ๐Ÿ“ The files

File Role
includes/services/assets.php getIgnoredServiceTags(), isUsableServiceTag(), resolveAssetIdentity() (reads only), updateAssetHostname(), reconcileAsset() (resolve + apply a rename), createDiscoveredAsset()
api/external/system-info/submit/index.php The inventory agent: reconcileAsset() then update, or createDiscoveredAsset()
api/external/software-inventory/submit/index.php The software agent: the same two calls (it only sends a hostname, so it always lands on tier 3)
includes/intune.php intuneLinkDevicesToAssets() โ€” renames for linked devices, then match-or-create for unlinked ones
includes/intune_user_history.php, includes/asset_assignment_source.php Every primary user a device has had, assets that follow it, and where each assignment came from (ยง6c, 5.3.0)
includes/intune_asset_type.php, api/intune/type_map.php Asset types from what each device is (ยง6d, 5.3.0)
includes/service_context.php ActorContext::system('Inventory agent' / 'Intune') โ€” the actor for changes no person made
asset-management/settings/ Discovery & reconciliation tab (the placeholder list, Cap::ASSETS_RECONCILIATION); the Intune tab is only a link since 5.4.0 ('moved_to' in the manifest)
system/integrations/microsoft365/intune.php, intune_import.php Intune's Connection (tenant, app, secret) and Import (Devices: company, renaming, primary users; Asset types; Software) - System โ†’ Integrations โ†’ Microsoft 365 since 5.4.0 (PR #352)
tests/asset-reconciliation.php 24 checks, one rolled-back transaction

๐Ÿ”‘ Every path that creates an asset now goes through AssetsService โ€” createAsset() for people, the REST API and imports; createDiscoveredAsset() for the agents and Intune. INSERT INTO assets appears in that one file and nowhere else. Keep it that way: it is what makes the tag, the transaction and the history row the same whichever source made the asset.

2. ๐Ÿชœ The tiers โ€” resolveAssetIdentity()

Tier 1  an authoritative connector link the caller already holds  -> that asset
Tier 2  a usable serial                                            -> the one asset with it
        ...but two or more assets share it                         -> no guess (ambiguous), unless serial AND name pick one
Tier 3  hostname                                                   -> that asset
        ...unless a usable serial CONTRADICTS it                   -> new asset, flagged hostname_reused
Tier 4  nothing                                                    -> new asset

It returns ['asset_id', 'matched_by', 'ambiguous', 'hostname_reused'] and writes nothing. reconcileAsset() wraps it and, for a match made by link or serial, applies a reported rename through updateAssetHostname().

๐Ÿ”ด The laptop refresh (tier 3)

A replacement laptop is very often given the old one's name. It reports a good serial nobody has seen, so tier 2 finds nothing โ€” and a plain hostname match would then write the new serial onto the old laptop's record. One record would describe two machines: the old one's purchase date and warranty now belong to the new one, and the old one, sitting in a cupboard for reuse, has no record at all.

So a hostname match only counts if it cannot contradict the serial:

$contradicts = $serialUsable && self::isUsableServiceTag($theirs, $ignoredTags)
            && strcasecmp($theirs, $serial) !== 0;

Both serials usable and different โ†’ a different machine โ†’ tier 4, with hostname_reused = the old asset's id. createDiscoveredAsset() records that in the new asset's history (hostname_reused, value #<id>) so a person sees it and renames or retires the old one.

The case this must not break: an asset entered without a serial (by hand, or before the agent ran) still matches by name. That is how the agent finds a hand-entered asset the first time, and fills its serial in.

The ambiguity guard (tier 2)

Two assets with the same serial (old duplicates, cloned VMs) are a question for a person. The resolver does not pick one. It accepts a match only if serial and hostname together identify exactly one โ€” Sandy's original fell back to the hostname alone, which could still pick the wrong twin.

3. ๐Ÿ™ˆ Placeholder serials

DEFAULT_IGNORED_SERVICE_TAGS โ€” TO BE FILLED BY O.E.M., DEFAULT STRING, NONE, SYSTEM SERIAL NUMBER, NOT SPECIFIED, 123456789 โ€” is what a motherboard reports when the maker never filled the field in. Matching on one would merge every such machine into one asset.

The list is editable (asset_reconciliation_ignored_serials, one per line, compared case-insensitively). A stored list replaces the defaults rather than adding to them, so an administrator can remove one that turns out to be a real serial on their estate.

4. โœ๏ธ Renames โ€” updateAssetHostname()

  • Hostname is unique per company, so a rename onto a name another asset in the asset's own company already has is skipped and reported as hostname_conflict. The asset's own company โ€” not the caller's โ€” because a person may have moved the asset since the source last saw it.
  • Truncated to 50 characters (assets.hostname is VARCHAR(50); Intune names can be 256).
  • Recorded in history through auditWrite() with no analyst (ActorContext::system() has actorId 0, written as NULL) and the source in the new value: LON-LT-042 (inventory agent).
  • ๐Ÿ”‘ The history write is best-effort. Before Database Verification has relaxed asset_history.analyst_id (it was NOT NULL), the write fails โ€” and an agent's whole report must not fail over its own audit row. It is logged with error_log() instead.

5. ๐Ÿ†• Creating โ€” createDiscoveredAsset()

Takes a whitelist of discovered columns, the company, the source and an optional hostname_reused. It runs through AssetTagsService::createWithTag(), so a company with automatic tags switched on gets one here too, inside the same transaction as the insert.

๐Ÿ”ด Its history row is asset_discovered, not asset_created. Database Verification's last_seen repair (#1583, api/system/db_verify.php) treats an asset_created row as proof that a person or an import made the record, and blanks last_seen wherever it equals first_seen โ€” which it does on every machine found by an agent. Writing asset_created here would have blanked last_seen on every newly discovered machine at the next verification. Don't "tidy" the two names together.

6. โ˜๏ธ Intune โ€” intuneLinkDevicesToAssets()

Behaviour
An existing link (intune_devices.asset_id) Trusted, wherever the asset now is. The MSP workflow is: a stub lands in one company, an analyst moves it to the client it belongs to (Moving an asset between companies). A link is never second-guessed because its asset is in a different company โ€” a person put it there.
A renamed device Found with one query (device_name โ‰  the asset's hostname), not a reconcile per device per sync. The asset takes the new name only if intune_sync_hostnames is on (below).
An unlinked device reconcileAsset() โ€” serial, then name โ€” in the company set under Intune โ†’ Import โ†’ Devices (System โ†’ Integrations โ†’ Microsoft 365; Assets โ†’ Settings โ†’ Intune before 5.4.0). Unset (every install after upgrade) matches across all companies, exactly as the old hostname-only link did. No match โ†’ createDiscoveredAsset() in that company (Default if unset).

intune_sync_hostnames โ€” off after an upgrade

On the install this was developed against, 65 of 582 linked devices had been renamed or reassigned in Intune since they were linked (NWUNIFI01 in Intune, still BWBUNIFI01 on the asset). Renaming them is the right result โ€” it's what the feature is for โ€” but doing it silently on the first sync after an upgrade breaks the rule that an upgrade changes nothing until somebody chooses to.

So it's a switch on Intune's Import page (the Intune tab before 5.4.0). freeitsm.sql seeds it '1' (a new install has nothing to rename) and Database Verification seeds '0'; INSERT IGNORE means a new install keeps its '1' and an upgraded one gets '0'.

6b. โ˜๏ธ Holders from Intune โ€” intuneAssignPrimaryUsers()

(4.8.0, PR #236 by vsc55; review: Assets from their Intune primary user - PR review.)

Called by intuneRunSync() straight after intuneLinkDevicesToAssets(), and (5.3.0, PR #334) by entraSyncRun() at the end of a live import through intuneAssignAfterDirectoryImport() - the join needs the device (an Intune sync) and the person's object id (an Entra import), so running it from one side only made the order of the two syncs decide whether an asset got a holder. Only when intune_assign_primary_user is '1'; the Entra side reads only that setting (the devices are already in intune_devices), never runs in a preview, and never fails the import - an error is logged. It gives each linked asset nobody holds to its device's primary user, through AssetsService::assignUser() with ActorContext::system('Intune') - so the assignment, the custody row, the asset's history and the asset.assigned workflows are exactly a manual assignment's.

๐Ÿ”‘ Matched by object id, never by name. A managed device's user_id (Graph userId) is the primary user's Entra object id. The Entra import stores the same id per person in user_sso_identities.source_ref (Entra directory sync - developer guide). One query joins them:

intune_devices d โ†’ assets a โ†’ user_sso_identities i (source_ref = d.user_id)
                 โ†’ auth_providers p (protocol = 'oidc') โ†’ users u (is_active = 1)
  where nobody holds the asset, the person's company is the asset's (NULL = Default),
        the asset is not retired
  group by asset having COUNT(DISTINCT u.id) = 1
Rule Where Why
Only an asset with no holder NOT EXISTS (โ€ฆ users_assets โ€ฆ) Who has a laptop is a fact a person may have corrected; Intune's primary user is often whoever enrolled it
Never unassign - It only fills gaps
Not a leaver u.is_active = 1
Not a retired asset assetNotRetiredSql() Retired kit keeps its last holder
Same company COALESCE(u.tenant_id, default) = COALESCE(a.tenant_id, default) The rule a company move enforces
One person per asset HAVING COUNT(DISTINCT u.id) = 1 Two linked devices naming two people is a question for a person, not a coin toss

Each asset is assigned in its own try: one failure is counted and logged ([intune] assign primary user to asset N) and the rest carry on; the sync's message adds how many were assigned to their primary user and, if any, how many could not be.

Setting. intune_assign_primary_user is '0' in freeitsm.sql and in Database Verification - unlike intune_sync_hostnames, a new install is off too, because this writes people's custody records. It is in the Intune tab's setting_keys in asset-management/settings/manifest.php, so the tab's permission covers it.

TRAP: an actor id of 0 is "nobody", never a foreign key. AssetsService::assignUser() used to write $ctx->actorId into users_assets.assigned_by_analyst_id and asset_checkout_log.analyst_id. The system actor's id is 0, which fk_users_assets_analyst refuses, so every automatic assignment failed (#2690, found by this PR). It now stores NULL, as auditWrite() already did. Any service method a system actor can call must do the same.

TRAP: source_ref has two readers. The Entra import writes it; this reads it. Change what the import stores there and assets silently stop being assigned - tests/intune-primary-user.php would catch it.

When it runs. Inside the Intune sync - started by the Sync button (api/intune/sync.php) or, since 5.3.0, by the scheduled job intune_sync (cron/intune_sync.php, Background jobs - Developer Guide ยง9) - and at the end of a live Entra import.

Test. FREEITSM_TEST_DATABASE=<throwaway db> php tests/intune-primary-user.php - 10 checks in a transaction that is always rolled back, with asset.assigned workflows paused for the run, pinning each rule above: an existing holder kept, a leaver skipped, two devices disagreeing skipped, an object id nobody imported skipped, another company's person skipped - and the assignment itself, stored with a NULL actor.

6c. โ˜๏ธ Primary user history and following - intuneFollowPrimaryUsers()

(5.3.0, PR #338 by vsc55, #335; review: Every primary user a device has had - PR review.)

ยง6b only fills a gap, and the sync overwrote intune_devices.user_id, so once an asset had a holder a laptop handed on in Intune was neither recorded nor followed. Three parts, all in includes/intune_user_history.php, run in this order by intuneRunSync() and by intuneAssignAfterDirectoryImport():

Step Function What it does
Record intuneRecordUserChange() From intuneUpsertDevice(), for every device read: a row in intune_device_user_history when a device is first seen (outcome first), then one each time its primary user differs from the last row. The person is matched by object id (intunePersonForObjectId(), the same join as ยง6b) and kept with the row
Assign intuneAssignPrimaryUsers() ยง6b, unchanged - fills assets nobody holds
Follow intuneFollowPrimaryUsers() Only when intune_follow_primary_user is '1' and intune_assign_primary_user is. Moves an asset Intune gave to somebody on to its device's new primary user
Resolve intuneResolveUserHistory() Says, for each new row, what FreeITSM did (IntuneUserOutcome): holder, not_imported, no_user, no_asset, not_assigned, analyst_holder, follow_off, skipped - for the asset's Intune tab

๐Ÿ”‘ Only a holder Intune put there is ever moved. Where every assignment came from is now on the row - users_assets.assigned_source, the AssetAssignmentSource enum (includes/asset_assignment_source.php):

enum AssetAssignmentSource: string
{
    case Analyst = 'analyst';   // somebody in the app
    case Intune  = 'intune';    // the Intune sync: a device's primary user
    case Api     = 'api';       // the REST API
    case System  = 'system';    // anything else running on its own

    public static function resolve($value, ActorContext $ctx): self
    {
        if ($value instanceof self) return $value;   // TRAP: never a string
        return self::fromContext($ctx);
    }
}

AssetsService::assignUser() stores AssetAssignmentSource::resolve($in['source'] ?? null, $ctx)->value (only once the column exists). Only the Intune code passes 'source' => AssetAssignmentSource::Intune; everything else gets the actor's source (ui โ†’ analyst, api โ†’ api, otherwise system).

TRAP: resolve() never honours a string, not even a valid one. The assign endpoints and the REST API hand their request body to AssetsService, so a string here would let a request say {"source":"intune"} and make a hand-made assignment one that Follow may move. Only code that holds the enum can name a source (merge fix on #338).

A row from before the column is NULL. assetAssignedByIntuneSql('ua') treats it as Intune's only when it has no analyst and Intune's custody note (AssetAssignmentSource::INTUNE_NOTE, Primary user of the device in Intune), and Database Verification fills those in as intune on every run (assetAssignmentSourceBackfill()). Every other NULL row is never moved.

The rules a move must pass - one query, then per asset an unassign and an assign through AssetsService as ActorContext::system('Intune'), in one transaction each, so the custody trail, the asset's history (from Ana to Ben) and the asset workflows all see an ordinary handover:

Rule Where
Exactly one holder, put there by Intune assetAssignedByIntuneSql('ua') and (SELECT COUNT(*) FROM users_assets x ...) = 1
The new person is somebody else, current, in the asset's company ua.user_id <> u.id, u.is_active = 1, the COALESCE(tenant_id, default) match of ยง6b
The asset's devices agree HAVING COUNT(DISTINCT u.id) = 1
Not retired assetNotRetiredSql()
Database Verification has run returns ['moved' => 0, 'failed' => 0] until users_assets.assigned_source exists (merge fix)

The disagreement. intuneAssetsWithDifferentUser() / intuneCountAssetsWithDifferentUser() - an asset with a holder whose linked device names a primary user none of its holders is (one row per asset) - feed the asset's Intune tab (api/intune/get_intune_device.php, which checks the asset's company like its neighbours) and System โ†’ Maintenance โ†’ Assets whose Intune user differs (system/intune-user-mismatch/, maintenanceCountIntuneMismatch()). Every company: Maintenance is administrators'.

Schema (needs Database Verification): intune_device_user_history (old and new object id, UPN, name and matched person; outcome; seen_datetime), users_assets.assigned_source. The asset merge moves the history rows (includes/services/asset_merge.php).

Test. FREEITSM_TEST_DATABASE=<throwaway db> php tests/intune-user-history.php - 27 checks, always rolled back: the history rows, each outcome, a follow with a positive control, a holder an analyst chose never moved, a string source refused, and nothing moving before the column exists.

6d. โ˜๏ธ Asset types from Intune - intuneApplyAssetTypes()

(5.3.0, PR #339 by vsc55, #336; review: Intune asset types - PR review.)

createDiscoveredAsset() is never given a type, so Intune's assets had none. Graph sends chassisType with every managed device; intuneRecordChassis() keeps it in intune_devices.chassis_type. Asset types are each install's own, so intune_type_map (a JSON setting, kind โ†’ asset_types.id) maps each IntuneDeviceKind to one of them. All in includes/intune_asset_type.php:

public static function fromDevice(?string $chassis, ?string $os): ?self
{
    switch (strtolower(trim((string)$chassis))) {
        case 'laptop':            return self::Laptop;
        case 'desktop':
        case 'worksworkstation':  return self::Desktop;   // Graph's own spelling
        case 'enterpriseserver':  return self::Server;
        case 'phone':             return self::Phone;
        case 'tablet':            return self::Tablet;
        case 'mobileother':
        case 'mobileunknown':     return self::OtherMobile;
    }
    // Unknown: only where the OS is unambiguous. A computer is never guessed.
    $os = strtolower((string)$os);
    if (str_contains($os, 'ios') || str_contains($os, 'ipados') || str_contains($os, 'android')) return self::OtherMobile;
    return null;
}

intuneRunSync() calls intuneApplyAssetTypes() straight after linking. It reads only assets with asset_type_id IS NULL (it fills, never changes), skips an asset whose devices say different kinds, and writes through AssetsService::updateFields() as ActorContext::system('Intune'), so each type is in the asset's history. Devices synced before the column are read from raw_json.

Company scope. intuneAssetTypesFor($conn, $companyId) - global types the company has not hidden, plus its own - decides what the mapping may offer and keep (for the Intune company, intuneTypeCompanyId()) and what an asset may be given (for the asset's own company). intuneTypeMap() drops a mapped type that has since been deleted, hidden or switched off.

The settings tab. api/intune/type_map.php returns the mapping, the usable types and intuneSuggestTypeMap() - a type whose name a kind is known by, compared by intuneNormaliseTypeName() (no case, no accents, plural allowed). A suggestion is shown as Suggested: X with Use, never pre-selected. Create (intuneCreateMissingTypes(), needs the asset-types permission too) gives each unmapped kind its suggested type, else a global type of that name, else a new global type, and saves. save_system_settings.php normalises intune_type_map to known kinds with positive ids, and the tab sends it only once it has loaded.

Known gap: intuneCreateMissingTypes() reuses a global type of the same name even when the Intune company has hidden it; intuneTypeMap() then drops it, so that kind maps to nothing. Skip a hidden match (or create a new type) if this is ever reported.

Test. FREEITSM_TEST_DATABASE=<throwaway db> php tests/intune-asset-type.php - 41 checks: every chassisType, the OS fallback, suggestions, Create, company scope, never overwriting a chosen type.

7. ๐Ÿข Companies

  • The agents match only within their key's company (tenant_id <=> ?, NULL-safe so a Default-company key matches NULL rows). Unchanged from before.
  • Intune โ€” see the table above. resolveAssetIdentity(..., $anyCompany = true) drops the company condition; nothing else should pass it.
  • idx_assets_tenant_service_tag (tenant_id, service_tag) serves tier 2.

8. โœ… Tests

php tests/asset-reconciliation.php โ€” 24 checks inside one transaction that is always rolled back, rows prefixed ZZREC-: placeholders; a renamed machine found by serial and renamed, with an analyst-less history row; the ambiguity guard with a positive control; the laptop refresh (new asset, flagged, old serial untouched) with a positive control; a rename collision; createDiscoveredAsset() writing asset_discovered; company isolation and "any company"; and Intune โ€” a moved asset keeps its link, an unlinked device links by serial with no stub, and renaming follows the setting. It runs against the install's real Intune devices too, inside the transaction, and leaves them as they were.

9. Extending it

  • Another source (vCenter, Jamf, a network scan): build an ActorContext::system('<source>'), call reconcileAsset(), and createDiscoveredAsset() on no match. Don't write an INSERT.
  • A stronger identifier โ€” the SMBIOS UUID is better than the serial for virtual machines (cloned VMs can share a serial). It would slot in between tier 1 and tier 2. Not MAC addresses: docks and Wi-Fi randomisation move them between machines.

See also: Asset tag numbering โ€” Developer Guide ยท The review (PR #164) ยท Inventory agent ยท Multi-Tenancy โ€” Developer Guide ยท Developer Tests โ€” Assets

โš ๏ธ **GitHub.com Fallback** โš ๏ธ