modVBAuthGlobalConstants.bas v2

' ============================================================
' Copyright (c) 2025-2026 Peter Bryant (Corylus Business Systems)
'                    and  Andrew Richards (The IT Service Ltd)
' Part of VBAuth - https://vbauth.com
' Licensed under the MIT Licence - see LICENCE.txt
' This copyright notice must not be removed or altered.
' Module version 2, for VBAuth 1.0.0.3
' ============================================================

Option Compare Database
Option Explicit

' ============================================================
' VBAuth API globals
' every one of these is written by SetEntraAPPIdValues and read
' by the feature modules, so a feature never touches
' lclVBAuthAdmin itself
' ============================================================
Public intAppID          As Integer  ' which lclVBAuthAdmin row to use, set by the caller before anything else
Public strClientID       As String   ' Entra app registration this call authenticates against
Public strTenantID       As String   ' Microsoft 365 tenant the registration belongs to
Public strScopeRequested As String   ' comma-separated Graph scopes this row claims
Public strBearerToken    As String   ' decoded token currently in hand, written by AcquireBearerToken
Public datBearerExpiry   As Date     ' UTC expiry of the token in hand, the only thing that ages it out
Public strGraphAPI_Verb  As String   ' HTTP verb the row calls for, GET, POST and so on
Public strGraphAPI_URL   As String   ' the endpoint assembled from the row's URL parts and any parameters
Public lngHTTPTimeout    As Long     ' milliseconds applied to all four MSXML2 timeout stages

' ============================================================
' token cache
' owned entirely by AcquireBearerToken and ClearTokenCache
' nothing outside this module reads or writes the array, and it
' never reaches disk
' ============================================================
Private Type TokenCacheEntry
    intAppID    As Integer  ' the lclVBAuthAdmin row this slot belongs to
    strClientID As String   ' registration the token was issued to, tested before any reuse
    strTenantID As String   ' tenant the token was issued in, tested before any reuse
    strToken    As String   ' the decoded bearer token itself
    datExpiry   As Date     ' UTC expiry, compared against UTCNow rather than Now
    strScopes   As String   ' scopes the token actually carries, stored normalised
End Type

Private tknCache()          As TokenCacheEntry  ' one slot per lclVBAuthAdmin row, sized on first use
Private intAdminRecordCount As Integer          ' slots in the array, and the flag that says it is built
Public strCachedClaims      As String           ' normalised scopes of the token in hand
Public strCachedClientID    As String           ' registration of the token in hand
Public strCachedTenantID    As String           ' tenant of the token in hand

' ============================================================
' database working variables
' these are Public for historical reasons and are used as scratch
' by SetEntraAPPIdValues, which closes and releases both before it
' returns - nothing else may rely on them surviving a call
' ============================================================
Public strMessage       As String   ' why the last call failed, in words fit to show a user
Public strSQL           As String   ' scratch SQL, overwritten on every call
Public db               As DAO.Database     ' scratch database handle, released by SetEntraAPPIdValues
Public rsAPIData        As DAO.Recordset    ' scratch admin row, closed and released by SetEntraAPPIdValues

' ============================================================
' general processing
' ============================================================
Public blnResult                As Boolean  ' shared return flag for callers that want one

' the three caching switches, set from your own startup code
' all default to False, so a fresh session does no caching at all
' until something turns it on
Public blnCheckExistingToken    As Boolean  ' True = Steps 1 and 2 active - reuse the token already in hand
Public blnUseRowCache           As Boolean  ' True = Step 3 active - reuse this AppID's own cached token
Public blnUseFullCache          As Boolean  ' True = Step 4 active - reuse another AppID's token on the same registration
Public strTokenSource           As String   ' which step supplied the last token, for diagnosis only
Public intTokenSourceAppID      As Integer  ' AppID whose cached token was used, 0 when none was

' ============================================================
' UTC clock
' expiry is compared in UTC because the DLL reports expiry in UTC
' local time would drift by the time zone offset, and by an hour
' again under British Summer Time
' ============================================================
Private Type SYSTEMTIME
    wYear           As Integer
    wMonth          As Integer
    wDayOfWeek      As Integer
    wDay            As Integer
    wHour           As Integer
    wMinute         As Integer
    wSecond         As Integer
    wMilliseconds   As Integer
End Type

#If VBA7 Then
    Private Declare PtrSafe Sub GetSystemTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)
#Else
    Private Declare Sub GetSystemTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)
#End If

' ============================================================
' sleep tool
' ============================================================
#If VBA7 Then
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal intMilliseconds As LongPtr)
#Else
    Public Declare Sub Sleep Lib "kernel32" (ByVal intMilliseconds As Long)
#End If

'where the setup wizard sends the user to create a registration
Public Const PORTAL_URL As String = _
    "https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/RegisteredApps"

' ============================================================
' UTCNow
' reads the machine clock in UTC through the kernel rather than
' converting from local time, so no time zone or BST assumption
' is made anywhere in the expiry logic
' returns the current UTC date and time to the second
' ============================================================
Private Function UTCNow() As Date
Dim st As SYSTEMTIME    ' filled by the API call, no disposal needed

    GetSystemTime st
    'milliseconds are dropped deliberately - token lifetimes are measured in minutes
    UTCNow = DateSerial(st.wYear, st.wMonth, st.wDay) + _
             TimeSerial(st.wHour, st.wMinute, st.wSecond)

End Function

' ============================================================
' SetEntraAPPIdValues
' loads the lclVBAuthAdmin row named by intAppID into the module
' globals and assembles the endpoint URL from its parts, so that
' a feature module never has to know the table exists
' returns False with strMessage set naming every missing field,
' and leaves all globals blanked so nothing stale can be used
'
' nothing here shows a dialog.  this is a library function and the
' caller owns the conversation with the user - it decides whether
' strMessage warrants a MsgBox, a status label or a log line
' ============================================================
Public Function SetEntraAPPIdValues(blnParam1 As Boolean, _
                                    blnParam2 As Boolean, _
                                    Optional strParam1 As String = "", _
                                    Optional strParam2 As String = "") As Boolean
Dim intCount    As Integer  ' how many rows match intAppID, used only to prove one exists
Dim strURLPart1 As String   ' the fixed opening of the endpoint, always present
Dim strURLPart2 As String   ' what follows parameter 1, empty when the row takes no parameter
Dim strURLPart3 As String   ' what follows parameter 2, empty when the row takes only one

    'default to failure and blank every global, so a caller that ignores the return
    'value cannot act on values left behind by an earlier call
    SetEntraAPPIdValues = False
    strGraphAPI_URL = ""
    strGraphAPI_Verb = ""
    strScopeRequested = ""
    strClientID = ""
    strTenantID = ""
    strMessage = ""

    If blnParam2 = True And blnParam1 = False Then
        'the URL is built in order, so a second parameter with no first has nowhere to go
        strMessage = "Parameter 2 cannot be requested without Parameter 1."
        GoTo CloseOut
    End If

    'prove the row exists before opening a recordset, so a missing AppID gives a clear
    'message rather than an empty recordset the caller has to interpret
    intCount = Nz(DCount("[AppID]", "lclVBAuthAdmin", "[AppID] = " & intAppID), 0)
    If intCount = 0 Then
        strMessage = "There is no record in lclVBAuthAdmin for AppID " & intAppID
        GoTo CloseOut
    End If

    'read the row itself
    strSQL = "SELECT * FROM lclVBAuthAdmin WHERE AppID = " & intAppID
    Set db = CurrentDb()
    Set rsAPIData = db.OpenRecordset(strSQL)

    If rsAPIData.BOF And rsAPIData.EOF Then
        'the count above said the row was there, so an empty recordset means it went
        'away between the two reads
        strMessage = "The record for AppID " & intAppID & " is missing from lclVBAuthAdmin"
        GoTo CloseOut
    End If

    'collect every missing field before reporting, so the user fixes the row once rather
    'than being sent round the loop one field at a time
    If IsNull(rsAPIData!Verb) Then
        SetEntraAPPIdValues = False
        strMessage = strMessage & "The API verb is missing." & vbCrLf
    End If
    If IsNull(rsAPIData!ScopeClaims) Then
        SetEntraAPPIdValues = False
        strMessage = strMessage & "The scope claims is missing." & vbCrLf
    End If
    If IsNull(rsAPIData!ClientID) Then
        SetEntraAPPIdValues = False
        strMessage = strMessage & "The ClientID is missing." & vbCrLf
    End If
    If IsNull(rsAPIData!TenantID) Then
        SetEntraAPPIdValues = False
        strMessage = strMessage & "The TenantID is missing." & vbCrLf
    End If
    If IsNull(rsAPIData!URLPart1) Then
        SetEntraAPPIdValues = False
        strMessage = strMessage & "The first part of the URL is missing." & vbCrLf
    End If

    If strMessage <> "" Then
        'strMessage already names every field that failed, so nothing is added here
        GoTo CloseOut
    End If

    'the row is complete, so publish it to the globals the feature modules read
    strClientID = rsAPIData!ClientID
    strTenantID = rsAPIData!TenantID
    strGraphAPI_Verb = rsAPIData!Verb
    strScopeRequested = rsAPIData!ScopeClaims
    strURLPart1 = rsAPIData!URLPart1
    strURLPart2 = Nz(rsAPIData!URLPart2, "")
    strURLPart3 = Nz(rsAPIData!URLPart3, "")

    'the endpoint always opens with part 1, whatever parameters follow
    strGraphAPI_URL = Trim(strURLPart1)

    'WaitForLogin is held in seconds for the user's benefit but MSXML2 wants milliseconds,
    'and it governs all four stages - resolve, connect, send and receive
    'a row that never had a value falls back to a minute
    lngHTTPTimeout = Nz(rsAPIData!WaitForLogin, 60) * 1000

    If blnParam1 = True Then
        If strParam1 <> "" Then
            strGraphAPI_URL = strGraphAPI_URL & strParam1
            'part 2 only has meaning once parameter 1 has been placed
            If strURLPart2 <> "" Then
                strGraphAPI_URL = strGraphAPI_URL & strURLPart2
            End If
        Else
            'the row was told to expect a parameter and the caller did not supply one
            strMessage = strMessage & "Parameter 1 is requested but not supplied." & vbCrLf
            GoTo CloseOut
        End If
    End If

    If blnParam2 = True Then
        If strParam2 <> "" Then
            strGraphAPI_URL = strGraphAPI_URL & strParam2
            'part 3 closes the endpoint after the second parameter
            If strURLPart3 <> "" Then
                strGraphAPI_URL = strGraphAPI_URL & strURLPart3
            End If
        Else
            strMessage = strMessage & "Parameter 2 is requested but not supplied." & vbCrLf
            GoTo CloseOut
        End If
    End If

    strGraphAPI_URL = Trim(strGraphAPI_URL)
    SetEntraAPPIdValues = True

CloseOut:
    'close the recordset before releasing it
    If Not rsAPIData Is Nothing Then
        rsAPIData.Close
    End If
    'close the database handle
    If Not db Is Nothing Then
        db.Close
    End If
    'release the recordset
    Set rsAPIData = Nothing
    'release the database handle
    Set db = Nothing

End Function

' ============================================================
' AcquireBearerToken
' supplies a bearer token for the current intAppID, reusing one
' already held wherever that is safe and calling the DLL only
' when it is not
' returns False with strMessage set and every token global
' blanked, so a failed call can never leave a usable token behind
'
' the five steps, tried in order, first one that can answer wins
' all expiry tests are in UTC
'   1. token in hand, same registration, scopes match exactly    (blnCheckExistingToken)
'   2. token in hand, same registration, scopes are a superset   (blnCheckExistingToken)
'   3. cache slot for THIS AppID, same registration              (blnUseRowCache)
'   4. cache slot for ANY OTHER AppID, same registration,
'      whose scopes cover the request                            (blnUseFullCache)
'   5. call the DLL, store what comes back, return it
'
' the switches default to False, so nothing above step 5 runs
' until the calling application turns it on, normally in startup
' code - the demo database drives them from a caching level
' control so each step can be shown working on its own
'
' there is deliberately no fifth level of reuse across
' registrations.  it would work: Graph validates the signature,
' audience, issuer, expiry and scp claim rather than which
' application asked.  it is refused because the consent grant,
' the sign-in audit entry and any Conditional Access policy all
' belong to the registration that obtained the token.  reusing it
' elsewhere would let a feature reach the user's data through a
' registration never consented for it, would name the wrong
' application in the tenant sign-in logs, would sidestep
' Conditional Access written for the calling application, and
' would mean disabling that application in Entra no longer
' stopped its features working
'
' so every reuse path below tests ClientID and TenantID before it
' looks at scopes at all.  what is technically possible and what
' is correct point in opposite directions here
' ============================================================
Public Function AcquireBearerToken(ByVal strClientIDIn As String, _
                                   ByVal strTenantIDIn As String, _
                                   ByVal strScopesIn As String) As Boolean
Dim strJson         As String   ' raw JSON the DLL returns, parsed and then discarded
Dim auth            As VBAuth.GraphAuthenticator   ' the DLL itself, released as soon as it has answered
Dim objJson         As Object   ' parsed JSON, released before exit
Dim objXml          As Object   ' XML document used only as a base64 decoder, released before exit
Dim objNode         As Object   ' the node inside it holding the encoded token, released before exit
Dim dbAdmin         As DAO.Database     ' local handle used only to size the cache, released before exit
Dim rsAdmin         As DAO.Recordset    ' AppID list used only to size the cache, closed and released
Dim intIndex        As Integer  ' cache slot under inspection, reused by several steps
Dim strScopesNorm   As String   ' the request's scopes normalised once, then compared repeatedly

    On Error GoTo ErrHandler

    'clear the diagnostics before anything can set them, so a stale value from the previous
    'call cannot be mistaken for this one
    strTokenSource = ""
    intTokenSourceAppID = 0

    'normalise once here rather than inside each comparison below
    strScopesNorm = NormaliseScopeClaims(strScopesIn)

    'build the cache on the first call of the session, and again after ClearTokenCache,
    'which resets the count precisely so that new lclVBAuthAdmin rows are picked up
    If intAdminRecordCount = 0 Then
        intAdminRecordCount = Nz(DCount("[AppID]", "lclVBAuthAdmin"), 0)
        If intAdminRecordCount = 0 Then
            'an empty admin table means there is nothing to authenticate against
            strMessage = "lclVBAuthAdmin contains no records."
            strTokenSource = "Not attempted - no lclVBAuthAdmin records"
            GoTo CleanExit
        End If

        ReDim tknCache(1 To intAdminRecordCount)

        'one slot per row, in AppID order, so a slot can be found by AppID later
        Set dbAdmin = CurrentDb
        Set rsAdmin = dbAdmin.OpenRecordset( _
            "SELECT AppID FROM lclVBAuthAdmin ORDER BY AppID", dbOpenSnapshot, dbReadOnly)
        intIndex = 1
        Do While Not rsAdmin.EOF
            tknCache(intIndex).intAppID = rsAdmin!AppID
            intIndex = intIndex + 1
            rsAdmin.MoveNext
        Loop
        'close the recordset before releasing it
        rsAdmin.Close
        'release the recordset
        Set rsAdmin = Nothing
        'close the database handle before releasing it
        dbAdmin.Close
        'release the database handle
        Set dbAdmin = Nothing
    End If

    'steps 1 and 2 both look at the token already in hand
    If blnCheckExistingToken Then

        'step 1 - an exact scope match
        'this is a strict subset of step 2 and could be folded into it, but it is kept
        'separate so strTokenSource can say which of the two actually answered
        If strBearerToken <> "" And datBearerExpiry > UTCNow() Then
            'registration first, scopes second - never the other way round
            If strCachedClientID = strClientIDIn And strCachedTenantID = strTenantIDIn Then
                'strCachedClaims is stored normalised, so the call here is belt and braces
                If strScopesNorm = NormaliseScopeClaims(strCachedClaims) Then
                    strTokenSource = "Step 1 - current token, scopes match exactly"
                    AcquireBearerToken = True
                    GoTo CleanExit
                End If
            End If
        End If

        'step 2 - a different action, but the token in hand already covers what it needs
        If strBearerToken <> "" And datBearerExpiry > UTCNow() Then
            If strCachedClientID = strClientIDIn And strCachedTenantID = strTenantIDIn Then
                If AreScopesSubset(strScopesNorm, strCachedClaims) Then
                    strTokenSource = "Step 2 - current token, scopes covered"
                    AcquireBearerToken = True
                    GoTo CleanExit
                End If
            End If
        End If
    End If

    'step 3 - this action's own slot, which survives a visit to other features
    If blnUseRowCache Then
        intIndex = CacheIndexForAppID(intAppID)
        If intIndex > 0 Then
            If tknCache(intIndex).strToken <> "" And tknCache(intIndex).datExpiry > UTCNow() Then
                'the slot belongs to this AppID, but the registration behind it may have
                'been changed since the token was stored, so test it anyway
                If tknCache(intIndex).strClientID = strClientIDIn And tknCache(intIndex).strTenantID = strTenantIDIn Then
                    strBearerToken = tknCache(intIndex).strToken
                    datBearerExpiry = tknCache(intIndex).datExpiry
                    strCachedClaims = tknCache(intIndex).strScopes
                    strCachedClientID = tknCache(intIndex).strClientID
                    strCachedTenantID = tknCache(intIndex).strTenantID
                    strTokenSource = "Step 3 - this action's own cached token"
                    intTokenSourceAppID = intAppID
                    AcquireBearerToken = True
                    GoTo CleanExit
                End If
            End If
        End If
    End If

    'step 4 - another action's slot, where it shares the registration and its scopes are
    'wide enough
    'the registration test is what makes this safe and is not optional - see the header
    If blnUseFullCache Then
        For intIndex = 1 To intAdminRecordCount
            If tknCache(intIndex).intAppID <> intAppID Then
                If tknCache(intIndex).strToken <> "" And tknCache(intIndex).datExpiry > UTCNow() Then
                    If tknCache(intIndex).strClientID = strClientIDIn And tknCache(intIndex).strTenantID = strTenantIDIn Then
                        If AreScopesSubset(strScopesNorm, tknCache(intIndex).strScopes) Then
                            strBearerToken = tknCache(intIndex).strToken
                            datBearerExpiry = tknCache(intIndex).datExpiry
                            strCachedClaims = tknCache(intIndex).strScopes
                            strCachedClientID = tknCache(intIndex).strClientID
                            strCachedTenantID = tknCache(intIndex).strTenantID
                            intTokenSourceAppID = tknCache(intIndex).intAppID
                            strTokenSource = "Step 4 - cached token from AppID " & intTokenSourceAppID
                            AcquireBearerToken = True
                            GoTo CleanExit
                        End If
                    End If
                End If
            End If
        Next intIndex
    End If

    'step 5 - nothing held will serve, so blank the globals before going to the DLL
    'blanking first means a failure below cannot leave the previous token in place
    strBearerToken = ""
    datBearerExpiry = CDate(0)
    strCachedClaims = ""
    strCachedClientID = ""
    strCachedTenantID = ""

    'this is the only line in the module that can raise a sign-in prompt
    Set auth = New VBAuth.GraphAuthenticator
    strJson = auth.GetAccessToken(strClientIDIn, strTenantIDIn, strScopesIn)
    'release the DLL as soon as it has answered
    Set auth = Nothing

    Set objJson = JSONConverter.ParseJson(strJson)

    If objJson("success") = False Then
        'the DLL reports its own failure in words, so pass those on rather than inventing any
        strMessage = "Failed to get access token: " & objJson("error")
        strTokenSource = "Step 5 - sign-in failed"
        AcquireBearerToken = False
        GoTo CleanExit
    End If

    'the DLL returns the token base64-encoded, and MSXML is used purely as a decoder
    'the version is pinned because the version-less ProgID binds MSXML3
    Set objXml = CreateObject("MSXML2.DOMDocument.6.0")
    Set objNode = objXml.createElement("b64")
    objNode.DataType = "bin.base64"
    objNode.Text = objJson("access_token")
    strBearerToken = StrConv(objNode.nodeTypedValue, vbUnicode)

    'record what the token actually carries, normalised, so later comparisons are reliable
    strCachedClaims = strScopesNorm
    strCachedClientID = strClientIDIn
    strCachedTenantID = strTenantIDIn

    'release the decoder node
    Set objNode = Nothing
    'release the decoder document
    Set objXml = Nothing

    'expiry is picked out of the ISO 8601 string by position rather than with CDate, which
    'would read the same characters differently under a non-UK locale
    datBearerExpiry = DateSerial(CInt(Left(objJson("expires_on"), 4)), _
                                 CInt(Mid(objJson("expires_on"), 6, 2)), _
                                 CInt(Mid(objJson("expires_on"), 9, 2))) + _
                      TimeSerial(CInt(Mid(objJson("expires_on"), 12, 2)), _
                                 CInt(Mid(objJson("expires_on"), 15, 2)), _
                                 CInt(Mid(objJson("expires_on"), 18, 2)))

    'file the token in this AppID's slot so steps 3 and 4 can find it next time
    intIndex = CacheIndexForAppID(intAppID)
    If intIndex > 0 Then
        tknCache(intIndex).strClientID = strClientIDIn
        tknCache(intIndex).strTenantID = strTenantIDIn
        tknCache(intIndex).strToken = strBearerToken
        tknCache(intIndex).datExpiry = datBearerExpiry
        tknCache(intIndex).strScopes = strCachedClaims
    End If

    'release the parsed JSON
    Set objJson = Nothing

    strTokenSource = "Step 5 - new token, interactive sign-in"
    intTokenSourceAppID = intAppID
    AcquireBearerToken = True

CleanExit:
    Exit Function

ErrHandler:
    'an unexpected failure must not leave a half-set token behind, so everything is blanked
    'before the error is reported
    strBearerToken = ""
    datBearerExpiry = CDate(0)
    strCachedClaims = ""
    strCachedClientID = ""
    strCachedTenantID = ""
    strMessage = "Unexpected error in AcquireBearerToken: " & Err.Description
    AcquireBearerToken = False
    strTokenSource = "Error"

    'an error can arrive at any point in the procedure, so this releases the full set
    'rather than working out which of the six were actually held - releasing an object
    'that is already Nothing is harmless, and the two DAO objects are guarded because
    'closing one that is Nothing is not
    'children before parents, and in the reverse of the order they were acquired
    'release the decoder node
    Set objNode = Nothing
    'release the decoder document
    Set objXml = Nothing
    'release the parsed JSON
    Set objJson = Nothing
    'release the DLL
    Set auth = Nothing
    'close the recordset before releasing it
    If Not rsAdmin Is Nothing Then
        rsAdmin.Close
    End If
    'release the recordset
    Set rsAdmin = Nothing
    'close the database handle before releasing it
    If Not dbAdmin Is Nothing Then
        dbAdmin.Close
    End If
    'release the database handle
    Set dbAdmin = Nothing

    Resume CleanExit

End Function

' ============================================================
' CacheIndexForAppID
' finds the cache slot belonging to an AppID
' returns 0 when the AppID has no slot, which happens when a row
' was added to lclVBAuthAdmin after the array was built
'
' the loop runs to completion and the answer is carried in the
' return value, which doubles as the found flag - the same shape
' as AreScopesSubset, and for the same reason
' the cost is the remainder of a pass over an array holding one
' slot per lclVBAuthAdmin row, which is a handful of integer
' comparisons
' ============================================================
Private Function CacheIndexForAppID(ByVal intID As Integer) As Integer
Dim i As Integer    ' slot under inspection

    'assume no slot, and let the loop below overturn it
    'nothing found leaves this as the answer, which happens when a row was added to
    'lclVBAuthAdmin since the array was built
    CacheIndexForAppID = 0

    'there can only be one match, because the array is built one slot per lclVBAuthAdmin
    'row, so once the slot is found the remaining passes do nothing
    For i = 1 To intAdminRecordCount
        If CacheIndexForAppID = 0 Then
            If tknCache(i).intAppID = intID Then
                CacheIndexForAppID = i
            End If
        End If
    Next i

End Function

' ============================================================
' ClearTokenCache
' empties every cache slot and the token currently in hand, so
' that the next call of any feature authenticates afresh
' returns nothing and cannot fail
'
' clearing the array alone would not be enough - step 1 would go
' on serving the token in strBearerToken and the call would look
' as though it had done nothing
'
' resetting intAdminRecordCount is what forces the array to be
' rebuilt from lclVBAuthAdmin, so rows added during the session
' are picked up
'
' this is a local clear only.  it does not reach into MSAL inside
' the DLL, so if the browser session is still live the next
' sign-in may complete without asking for credentials again
'
' nothing is shown to the user from here - the caller owns that
' ============================================================
Public Sub ClearTokenCache()
Dim i As Integer    ' slot being emptied

    'the AppID in each slot is left alone - the slot still belongs to that row
    If intAdminRecordCount > 0 Then
        For i = 1 To intAdminRecordCount
            tknCache(i).strClientID = ""
            tknCache(i).strTenantID = ""
            tknCache(i).strToken = ""
            tknCache(i).datExpiry = CDate(0)
            tknCache(i).strScopes = ""
        Next i
    End If

    'rebuild the array on the next call so any new rows are included
    intAdminRecordCount = 0

    'clear the token in hand as well, or step 1 would serve it straight back
    strBearerToken = ""
    datBearerExpiry = CDate(0)
    strCachedClaims = ""
    strCachedClientID = ""
    strCachedTenantID = ""
    strTokenSource = "Cache cleared - no token held"
    intTokenSourceAppID = 0

End Sub

' ============================================================
' AreScopesSubset
' decides whether a cached token is wide enough for a request,
' by testing that every requested scope appears in the cached set
' returns True only when every requested scope is accounted for
' comparison is case-insensitive, and both arguments are
' comma-separated scope names
'
' both loops run to completion rather than breaking out, which is
' the house rule, and the answer is carried in blnAllFound instead
' the cost of that is one extra pass over the cached list for each
' scope that matches early, and it is accepted: a scope list is a
' handful of short strings, so the worst case here is a few dozen
' string comparisons against a token request that will otherwise
' cost a network round trip and possibly an interactive sign-in
'
' the outer body is wrapped in a test of blnAllFound so that once
' one requested scope has gone unmatched the answer cannot change
' and no further comparisons are made - the loop still runs to its
' natural end, it simply stops doing any work
' ============================================================
Private Function AreScopesSubset(strRequested As String, strCached As String) As Boolean
Dim arrRequested()  As String   ' the scopes this call needs
Dim arrCached()     As String   ' the scopes the held token actually carries
Dim strScope        As String   ' the requested scope being looked for
Dim blnFound        As Boolean  ' whether the current scope was matched
Dim blnAllFound     As Boolean  ' whether every scope so far has been matched, the running answer
Dim i               As Integer  ' cursor over the requested scopes
Dim j               As Integer  ' cursor over the cached scopes

    arrRequested = Split(strRequested, ",")
    arrCached = Split(strCached, ",")

    'start from "the cached token covers this" and let the loop below overturn it
    blnAllFound = True

    'every requested scope has to appear in the cached set, and one that does not is
    'enough to disqualify the whole cached token
    For i = 0 To UBound(arrRequested)
        If blnAllFound = True Then
            strScope = Trim(arrRequested(i))
            blnFound = False
            For j = 0 To UBound(arrCached)
                If StrComp(strScope, Trim(arrCached(j)), vbTextCompare) = 0 Then
                    blnFound = True
                End If
            Next j
            If blnFound = False Then
                blnAllFound = False
            End If
        End If
    Next i

    AreScopesSubset = blnAllFound

End Function

' ============================================================
' NormaliseScopeClaims
' puts a scope list into a form two lists can be compared in, by
' trimming each claim and sorting them alphabetically
' returns an empty string for empty input, so a blank row never
' matches anything by accident
'
' used by AcquireBearerToken to compare requested against cached
' scopes, and by FindSharedRegistration to recognise two rows
' that describe the same Azure app registration
' ============================================================
Public Function NormaliseScopeClaims(ByVal strClaims As String) As String
Dim arrClaims()     As String   ' the claims being trimmed and sorted in place
Dim i               As Integer  ' outer sort cursor, also used for the trim pass
Dim j               As Integer  ' inner sort cursor
Dim strTemp         As String   ' swap holder for the sort

    strClaims = Trim(strClaims)

    'nothing in means nothing out, and the caller treats empty as no match
    If strClaims = "" Then
        NormaliseScopeClaims = ""
        Exit Function
    End If

    arrClaims = Split(strClaims, ",")

    'spacing after the commas is a matter of taste in the table, so remove it here
    For i = 0 To UBound(arrClaims)
        arrClaims(i) = Trim(arrClaims(i))
    Next i

    'a bubble sort is ample - a scope list is a handful of entries, not a data set
    'the comparison is case-insensitive so that Mail.Read and mail.read sort together
    For i = 0 To UBound(arrClaims) - 1
        For j = 0 To UBound(arrClaims) - 1 - i
            If StrComp(arrClaims(j), arrClaims(j + 1), vbTextCompare) > 0 Then
                strTemp = arrClaims(j)
                arrClaims(j) = arrClaims(j + 1)
                arrClaims(j + 1) = strTemp
            End If
        Next j
    Next i

    NormaliseScopeClaims = Join(arrClaims, ",")

End Function

' ============================================================
' FindSharedRegistration
' finds another lclVBAuthAdmin row that already holds a ClientID
' and claims exactly the same scopes, so that one registration
' can serve both rows instead of the user creating a second
' returns False with every out-parameter blank when there is no
' such row
'
' a failed read also returns False, but sets strMessage while
' doing so, which is how the caller tells "nothing matched" from
' "the lookup broke".  before this had its own error handler the
' two were indistinguishable, and a missing column in
' lclVBAuthAdmin would silently stop ClientID propagation working
' with no symptom at all
'
' lngExcludeAppID is normally the row being configured, so that
' it cannot match itself
' ============================================================
Public Function FindSharedRegistration(ByVal lngTargetAppID As Long, _
                                       ByVal lngExcludeAppID As Long, _
                                       ByRef lngMatchAppID As Long, _
                                       ByRef strMatchClientID As String, _
                                       ByRef strMatchObjectID As String, _
                                       ByRef strMatchTenantID As String) As Boolean
Dim db               As DAO.Database    ' local handle, shadows the module global, released below
Dim rs               As DAO.Recordset   ' candidate rows, closed and released below
Dim strTargetNorm    As String  ' the scopes we are trying to match, normalised once
Dim strCandidateNorm As String  ' the candidate row's scopes, normalised for comparison

    'assume no match, and blank the out-parameters so a caller that ignores the return
    'value cannot read values left by a previous call
    FindSharedRegistration = False
    lngMatchAppID = 0
    strMatchClientID = ""
    strMatchObjectID = ""
    strMatchTenantID = ""

    'strMessage is left alone until something actually goes wrong, so that a plain
    'no-match does not overwrite a message the caller has not read yet
    On Error GoTo ErrHandler

    strTargetNorm = NormaliseScopeClaims( _
        Nz(DLookup("ScopeClaims", "lclVBAuthAdmin", "AppID = " & lngTargetAppID), ""))

    If strTargetNorm = "" Then
        'a row claiming no scopes would match every other empty row, which is not a match
        GoTo CloseOut
    End If

    'only rows that already have a ClientID are worth comparing - a row without one has
    'no registration to share
    Set db = CurrentDb
    Set rs = db.OpenRecordset( _
        "SELECT AppID, ScopeClaims, ClientID, ObjectID, TenantID " & _
        "FROM lclVBAuthAdmin " & _
        "WHERE AppID <> " & lngExcludeAppID & _
        " AND (ClientID IS NOT NULL AND ClientID <> '')", _
        dbOpenSnapshot)

    Do While Not rs.EOF
        strCandidateNorm = NormaliseScopeClaims(Nz(rs!ScopeClaims, ""))
        'the scopes must be identical, not merely overlapping - a wider registration is
        'not the same registration
        If StrComp(strTargetNorm, strCandidateNorm, vbTextCompare) = 0 Then
            lngMatchAppID = CLng(rs!AppID)
            strMatchClientID = Nz(rs!ClientID, "")
            strMatchObjectID = Nz(rs!ObjectID, "")
            strMatchTenantID = Nz(rs!TenantID, "")
            FindSharedRegistration = True
            GoTo CloseOut
        End If
        rs.MoveNext
    Loop

CloseOut:
    'close the recordset before releasing it
    If Not rs Is Nothing Then
        rs.Close
    End If
    'release the recordset
    Set rs = Nothing
    'close the database handle before releasing it
    If Not db Is Nothing Then
        db.Close
    End If
    'release the database handle
    Set db = Nothing
    Exit Function

ErrHandler:
    'a broken read is not the same answer as "no matching registration", so it says so
    'the out-parameters were blanked at the top and nothing partial is left behind, since
    'they are only written once a match is complete
    FindSharedRegistration = False
    lngMatchAppID = 0
    strMatchClientID = ""
    strMatchObjectID = ""
    strMatchTenantID = ""
    strMessage = "Could not search for a shared registration: " & Err.Description
    Resume CloseOut

End Function

' ============================================================
' GetVBAuthLogPath
' gives the full path of the DLL's diagnostic log, which the DLL
' writes to the user's own temp folder
' returns the path whether or not the file exists yet
' ============================================================
Public Function GetVBAuthLogPath() As String

    GetVBAuthLogPath = Environ("LOCALAPPDATA") & "\Temp\VBAuth.log"

End Function

' ============================================================
' IsValidGUID
' tests whether a string has the shape of a GUID, so that a
' Client ID or Tenant ID pasted into a text box can be rejected
' before it is stored and before a sign-in is attempted with it
' returns True for 8-4-4-4-12 characters separated by hyphens
'
' this is a shape test, not a validity test.  it does not check
' that the characters are hexadecimal, and it cannot know whether
' the GUID names a real registration - only Entra can tell you
' that.  it exists to catch the common paste mistakes: a
' truncated value, a value with the surrounding quotes still on
' it, or an application name pasted instead of an ID
'
' it lived twice as a Private copy, in frmConfigureFeature and
' frmSetupWizard, character for character.  it is here so there
' is one of it.  the two copies are deleted, and no call site
' changes - a Public function in a standard module is callable
' unqualified from a form
'
' the Exit Function calls are the shape of the procedure: each
' one is a length test that has already settled the answer, and
' nothing has been acquired that would need releasing
' ============================================================
Public Function IsValidGUID(strValue As String) As Boolean
Dim arrParts As Variant     ' the five hyphen-separated blocks, nothing to release

    'assume invalid, so every test below only has to bail out rather than restate it
    IsValidGUID = False

    'the total length is fixed, so anything else is settled without splitting
    If Len(strValue) <> 36 Then
        Exit Function
    End If

    arrParts = Split(strValue, "-")

    'four hyphens give five blocks - any other count is not a GUID
    If UBound(arrParts) <> 4 Then
        Exit Function
    End If

    'and each block has its own fixed length
    If Len(arrParts(0)) <> 8 Then
        Exit Function
    End If
    If Len(arrParts(1)) <> 4 Then
        Exit Function
    End If
    If Len(arrParts(2)) <> 4 Then
        Exit Function
    End If
    If Len(arrParts(3)) <> 4 Then
        Exit Function
    End If
    If Len(arrParts(4)) <> 12 Then
        Exit Function
    End If

    IsValidGUID = True

End FunctionCode language: PHP (php)
Updated on September 11, 2026