Documentation
¶
Overview ¶
Package auth account resolver middleware for multi-account support.
This file implements the AccountResolver middleware that resolves the correct Graph client for each tool call based on the "account" parameter, single-account auto-selection, or MCP Elicitation API prompting.
Package auth provides account persistence for multi-account configurations.
This file implements the JSON-based persistence layer for per-account identity configuration (client_id, tenant_id, auth_method). The accounts file stores only non-secret metadata; tokens and credentials are managed separately by the OS-native token cache.
Package auth clears token cache artifacts for an account's cache partition.
This file provides ClearTokenCache, used by account_logout (CR-0056) to delete the persisted token cache for a given partition name. It targets the file-based cache artifacts (CR-0037/CR-0038) unconditionally and attempts a best-effort OS keychain deletion via the build-tagged helper clearKeychainTokenCache (see cache_clear_cgo.go / cache_clear_nocgo.go).
Package auth context helpers for multi-account support.
This file defines context key types and helper functions for storing and retrieving per-request Graph clients and account authentication details. These are used by the AccountResolver middleware to inject the resolved account's client into the request context, and by tool handlers and the AuthMiddleware to retrieve them.
Package auth implements the authentication subsystem for the Outlook Calendar MCP Server. It provides configurable credential construction (interactive browser or device code flow, see CR-0024), persistent OS-native token cache initialization, authentication record persistence, authentication error detection, and an AuthMiddleware that intercepts auth errors from tool handlers to trigger re-authentication via MCP client notifications. Authentication is lazy: it is deferred to the first tool call rather than blocking at startup (see CR-0022). The Authenticator interface abstracts over both credential types, allowing the middleware to work with either without coupling to a specific implementation.
Package auth account email resolver for multi-account support.
This file provides EnsureEmail, a best-effort helper that lazily fetches the authenticated user's email address from the Microsoft Graph /me endpoint and caches it on the AccountEntry. Once set, the email is never re-fetched.
Package auth account registry for multi-account support.
This file defines the AccountRegistry, a thread-safe in-memory store for managing multiple authenticated Microsoft accounts. Each account is identified by a unique label and holds the credential, Graph client, and authentication metadata needed for per-request account resolution.
Package auth provides account restoration for multi-account configurations.
This file implements startup restoration of persisted accounts from the accounts JSON file. Each account is reconstructed using its persisted identity configuration (client_id, tenant_id, auth_method), and silent token acquisition is attempted to verify the cached credential. Accounts that fail silent auth are still registered in the registry for deferred re-authentication by the auth middleware.
Index ¶
- Variables
- func AccountResolver(registry *AccountRegistry) func(mcpserver.ToolHandlerFunc) mcpserver.ToolHandlerFunc
- func ActiveBackend() string
- func AddAccountConfig(path string, config AccountConfig) error
- func AuthMiddleware(cred Authenticator, authRecordPath string, authMethod string, scopes []string) (func(mcpserver.ToolHandlerFunc) mcpserver.ToolHandlerFunc, func())
- func AuthRecordDir(authRecordPath string) string
- func Authenticate(ctx context.Context, auth Authenticator, authRecordPath string, ...) (azidentity.AuthenticationRecord, error)
- func ClearTokenCache(name string) error
- func EnsureEmail(ctx context.Context, entry *AccountEntry)
- func EnsureEmailAndPersistUPN(ctx context.Context, entry *AccountEntry, accountsPath string)
- func FormatAuthError(err error) string
- func GraphClientFromContext(ctx context.Context) (*msgraphsdk.GraphServiceClient, bool)
- func InitCache(name, storage string) azidentity.Cache
- func InitMSALCache(name, storage string) msalcache.ExportReplace
- func IsAuthError(err error) bool
- func LoadAuthRecord(path string) azidentity.AuthenticationRecord
- func RemoveAccountConfig(path string, label string) error
- func ResolveTokenCacheBackend(name, storage string) string
- func RestoreAccounts(accountsPath string, cacheNameBase string, authRecordDir string, ...) (restored int, total int)
- func SaveAccounts(path string, accounts []AccountConfig) error
- func SaveAuthRecord(path string, record azidentity.AuthenticationRecord) error
- func Scopes(cfg config.Config) []string
- func UpdateAccountUPN(path string, label string, upn string) error
- func WithAccountAuth(ctx context.Context, auth AccountAuth) context.Context
- func WithAccountInfo(ctx context.Context, info AccountInfo) context.Context
- func WithGraphClient(ctx context.Context, client *msgraphsdk.GraphServiceClient) context.Context
- type AccountAuth
- type AccountConfig
- type AccountEntry
- type AccountInfo
- type AccountRegistry
- func (r *AccountRegistry) Add(entry *AccountEntry) error
- func (r *AccountRegistry) Count() int
- func (r *AccountRegistry) Get(label string) (*AccountEntry, bool)
- func (r *AccountRegistry) GetByUPN(upn string) (*AccountEntry, bool)
- func (r *AccountRegistry) Labels() []string
- func (r *AccountRegistry) List() []*AccountEntry
- func (r *AccountRegistry) ListAuthenticated() []*AccountEntry
- func (r *AccountRegistry) Remove(label string) error
- func (r *AccountRegistry) Update(label string, fn func(*AccountEntry)) error
- type AccountsFile
- type AuthCodeCredential
- func (c *AuthCodeCredential) Account() (public.Account, bool)
- func (c *AuthCodeCredential) AuthCodeURL(ctx context.Context, scopes []string) (string, error)
- func (c *AuthCodeCredential) Authenticate(_ context.Context, _ *policy.TokenRequestOptions) (azidentity.AuthenticationRecord, error)
- func (c *AuthCodeCredential) ExchangeCode(ctx context.Context, redirectURL string, scopes []string) error
- func (c *AuthCodeCredential) GetToken(ctx context.Context, options policy.TokenRequestOptions) (azcore.AccessToken, error)
- func (c *AuthCodeCredential) LoadPersistedAccount(path string) error
- func (c *AuthCodeCredential) PersistAccount(path string) error
- func (c *AuthCodeCredential) SetAccount(account public.Account)
- type AuthCodeFlow
- type Authenticator
- type CredentialFactory
- type GraphClientFactory
- type NewAuthCodeCredentialOption
Constants ¶
This section is empty.
Variables ¶
var DeviceCodeMsgKey = deviceCodeMsgKeyType{}
DeviceCodeMsgKey is the context key for injecting a chan string into the authentication context. The middleware and add_account handler write this channel so that deviceCodeUserPrompt can forward the device code message back, allowing callers to present it to the user.
Functions ¶
func AccountResolver ¶
func AccountResolver(registry *AccountRegistry) func(mcpserver.ToolHandlerFunc) mcpserver.ToolHandlerFunc
AccountResolver returns a middleware factory that resolves the correct Graph client for each tool call. The resolution strategy considers only authenticated accounts (Authenticated == true):
- If the request includes an "account" parameter, look up that label in the registry. Return an error if not found.
- If no "account" parameter and zero authenticated accounts exist, return an error instructing the user to authenticate via add_account.
- If no "account" parameter and exactly one authenticated account exists, auto-select it without elicitation.
- If no "account" parameter and multiple authenticated accounts exist, use the MCP Elicitation API to prompt the user to select an account.
- If elicitation returns accept, use the selected account. If decline or cancel, return an error. On any elicitation error, fall back to the "default" account.
After resolution, the middleware injects the Graph client via WithGraphClient and the account auth details via WithAccountAuth, then calls the next handler.
Parameters:
- registry: the account registry containing all authenticated accounts.
Returns a middleware function compatible with the tool handler wrapping pattern used in RegisterTools.
func ActiveBackend ¶ added in v0.5.0
func ActiveBackend() string
ActiveBackend returns the name of the currently-active token cache storage backend. The value is set by InitCache at server startup and does not change during the lifetime of the process.
Possible return values:
- "keychain" – tokens are stored in the OS keychain (macOS Keychain Services / Windows Credential Manager / Linux Secret Service).
- "file" – tokens are stored in an AES-256-GCM encrypted file under ~/.outlook-local-mcp/.
ActiveBackend is safe to call from any goroutine without synchronisation.
func AddAccountConfig ¶
func AddAccountConfig(path string, config AccountConfig) error
AddAccountConfig appends an account configuration to the persistent accounts file. The file is loaded, the new config is appended, and the file is saved atomically.
Parameters:
- path: absolute filesystem path to the accounts JSON file.
- config: the account configuration to add.
Returns an error if the file cannot be loaded or saved.
Side effects: modifies the accounts file at path.
func AuthMiddleware ¶
func AuthMiddleware(cred Authenticator, authRecordPath string, authMethod string, scopes []string) (func(mcpserver.ToolHandlerFunc) mcpserver.ToolHandlerFunc, func())
AuthMiddleware returns a middleware factory that wraps tool handlers with authentication error detection and automatic re-authentication. When the inner handler returns an authentication error (detected via IsAuthError on the Go error or auth error patterns in CallToolResult content), the middleware:
- Sends a LoggingMessageNotification to the MCP client indicating authentication is required.
- Calls Authenticate to initiate the authentication flow. For device code auth, the credential's UserPrompt callback fires during this call. For browser auth, the system browser is opened directly.
- On success, logs "server authenticated and ready to serve" (once), and retries the original tool call exactly once.
- On failure, returns an mcp.NewToolResultError with troubleshooting guidance from FormatAuthError.
A sync.Mutex ensures that only one re-authentication attempt runs at a time. Concurrent tool calls encountering auth errors wait for the single re-authentication to complete before retrying.
Fresh-credential detection: when neither preAuthenticated nor authenticated is true, the middleware assumes the credential has never been authenticated. In this case, it skips calling the inner handler (which would block for the Graph API timeout, typically 30 seconds) and immediately initiates the re-authentication flow. The startup token probe in main.go calls MarkPreAuthenticated to signal that the cached token is valid, preventing this fast-path from triggering for credentials with valid cached tokens.
Parameters:
- cred: the Authenticator constructed by SetupCredential.
- authRecordPath: absolute path for persisting the AuthenticationRecord.
- authMethod: the authentication method ("browser" or "device_code") that controls the re-authentication flow in handleAuthError. For "browser", the system browser is opened directly. For "device_code", the device code prompt is forwarded via the DeviceCodeMsgKey channel mechanism.
- scopes: OAuth scopes to request during authentication (from Scopes(cfg)).
Returns the middleware function compatible with the tool handler wrapping pattern used in RegisterTools, and a MarkPreAuthenticated callback that the startup token probe calls to signal that the credential has a valid cached token.
func AuthRecordDir ¶
AuthRecordDir extracts the directory path from an auth record file path. This is used to derive the per-account auth record directory from the server config's AuthRecordPath.
Parameters:
- authRecordPath: the full filesystem path to the auth record file.
Returns the directory component of the path.
func Authenticate ¶
func Authenticate(ctx context.Context, auth Authenticator, authRecordPath string, scopes []string) (azidentity.AuthenticationRecord, error)
Authenticate performs interactive authentication using the provided Authenticator and persists the resulting AuthenticationRecord to disk. This function is intended to be called by the AuthMiddleware when a tool call encounters an authentication error, rather than during server startup.
The Authenticator may be either an InteractiveBrowserCredential (which opens the system browser) or a DeviceCodeCredential (which invokes a UserPrompt callback), depending on the configured auth method.
Parameters:
- ctx: context for the authentication call. Should not be bound to a short-lived tool call deadline, since interactive authentication requires user action (up to ~15 minutes for device code flow).
- auth: the Authenticator to use for authentication.
- authRecordPath: absolute filesystem path where the AuthenticationRecord will be persisted on success.
- scopes: OAuth scopes to request (e.g., from Scopes(cfg)).
Returns the AuthenticationRecord on success, or an error if the authentication flow fails or the record cannot be saved.
Side effects: triggers interactive authentication (browser launch or device code prompt), writes the AuthenticationRecord to disk on success.
func ClearTokenCache ¶ added in v0.3.0
ClearTokenCache removes the persisted token cache for the given partition name. It deletes the file-based cache artifacts (`{name}.bin`, `{name}.cae.bin`, `{name}_msal.bin`) from the shared cache directory and attempts to delete the OS keychain entry on CGo-enabled builds. Missing files or unavailable keychain entries are not treated as errors; this function is best-effort (see CR-0056 Risk 3).
Parameters:
- name: the cache partition name (AccountEntry.CacheName).
Returns the first unexpected error encountered while deleting file cache artifacts, or nil on success. Missing-file conditions are ignored.
func EnsureEmail ¶ added in v0.2.1
func EnsureEmail(ctx context.Context, entry *AccountEntry)
EnsureEmail lazily fetches the authenticated user's email address from the Microsoft Graph API and caches it on entry.Email. If the email is already set or the entry has no Graph client, the function returns immediately. Failures are logged and silently ignored — callers should tolerate an empty email and degrade gracefully.
Parameters:
- ctx: the context for the Graph API call.
- entry: the account entry to populate. Email is set on success.
Side effects: calls GET /me on the Microsoft Graph API on first invocation per entry. Uses entry.emailMu to prevent concurrent fetches.
func EnsureEmailAndPersistUPN ¶ added in v0.3.0
func EnsureEmailAndPersistUPN(ctx context.Context, entry *AccountEntry, accountsPath string)
EnsureEmailAndPersistUPN behaves like EnsureEmail but additionally backfills the resolved value to the persistent accounts file when the corresponding entry's UPN is empty. This is the CR-0056 migration path: accounts that existed before the UPN field was introduced have their UPN persisted the first time the email is resolved, so subsequent restarts can populate AccountEntry.Email without a Graph /me call.
Parameters:
- ctx: context for the Graph API call.
- entry: the account entry to populate.
- accountsPath: filesystem path to accounts.json; when empty, no persistence is attempted (behaves exactly like EnsureEmail).
Side effects: may issue one GET /me call on first invocation per entry, and one atomic rewrite of accounts.json when the persisted UPN is empty. Persistence failures are logged and otherwise ignored so tool flows remain resilient to a read-only or misconfigured accounts file.
func FormatAuthError ¶
FormatAuthError returns an LLM-actionable error message for the given authentication error. The output includes a plain-language description of the failure and specific MCP tool names the LLM should call to recover. Raw Azure SDK class names (e.g., DeviceCodeCredential, InteractiveBrowserCredential) are stripped from the output so the LLM does not hallucinate SDK-level troubleshooting advice.
Parameters:
- err: the authentication error to format. Must not be nil.
Returns a multi-line string containing a plain-language description and recovery instructions referencing MCP tool names.
FormatAuthError is safe for concurrent use.
func GraphClientFromContext ¶
func GraphClientFromContext(ctx context.Context) (*msgraphsdk.GraphServiceClient, bool)
GraphClientFromContext retrieves the Graph client previously stored via WithGraphClient. Tool handlers call this to obtain the per-request client.
Parameters:
- ctx: the context to retrieve the client from.
Returns the client and true if present, or nil and false if not.
func InitCache ¶
func InitCache(name, storage string) azidentity.Cache
InitCache initializes a persistent token cache identified by name, using the storage backend specified by the storage parameter.
Storage behavior:
- "file": uses file-based AES-256-GCM encrypted cache directly, without attempting the OS keychain.
- "auto": attempts OS keychain first; falls back to file-based cache if the keychain is unavailable at runtime.
- "keychain": attempts OS keychain only. If unavailable, returns a zero-value cache (in-memory) and logs an error — no file-based fallback.
Parameters:
- name: the partition name that isolates this application's cached tokens from other applications.
- storage: the token storage backend preference ("auto", "keychain", or "file").
Returns an azidentity.Cache backed by the selected storage, or a zero-value azidentity.Cache when storage fails (in-memory only).
func InitMSALCache ¶
func InitMSALCache(name, storage string) msalcache.ExportReplace
InitMSALCache creates an MSAL-compatible persistent token cache accessor using the storage backend specified by the storage parameter.
Storage behavior:
- "file": uses file-based AES-256-GCM encrypted cache directly, without attempting the OS keychain.
- "auto": attempts OS keychain first; falls back to file-based cache if the keychain is unavailable at runtime.
- "keychain": attempts OS keychain only. If unavailable, returns nil and logs an error — no file-based fallback.
Parameters:
- name: the partition name that isolates this application's cached tokens from other applications. On macOS and Linux this is a service/label name; on Windows it is the path to a storage file.
- storage: the token storage backend preference ("auto", "keychain", or "file").
Returns the MSAL-compatible cache accessor, or nil when the selected storage is unavailable. A nil return causes the credential to fall back to MSAL's built-in in-memory cache.
func IsAuthError ¶
IsAuthError reports whether err represents an authentication failure that should trigger re-authentication.
The function checks three categories of evidence:
- The error message contains a known authentication-related substring (DeviceCodeCredential, InteractiveBrowserCredential, authentication required, or AADSTS).
- The error is a context deadline exceeded error originating from a credential operation (identified by "DeviceCodeCredential" or "InteractiveBrowserCredential" in the error chain text combined with context.DeadlineExceeded).
- The error is an ODataError with HTTP status 401 Unauthorized.
Parameters:
- err: the error to inspect. May be nil.
Returns true when the error matches any authentication failure pattern, false otherwise. A nil error always returns false.
IsAuthError is safe for concurrent use.
func LoadAuthRecord ¶
func LoadAuthRecord(path string) azidentity.AuthenticationRecord
LoadAuthRecord reads and deserializes a JSON-encoded AuthenticationRecord from the file at path. The AuthenticationRecord contains only non-secret metadata (account ID, tenant, authority) and is safe to store as plain JSON.
Parameters:
- path: absolute filesystem path to the authentication record JSON file.
Returns a populated AuthenticationRecord when the file exists and contains valid JSON, or a zero-value AuthenticationRecord when the file is missing or contains invalid JSON. Errors are logged but not propagated, since a missing or corrupt record simply triggers re-authentication.
func RemoveAccountConfig ¶
RemoveAccountConfig removes an account configuration by label from the persistent accounts file. If the label is not found, no error is returned and the file is unchanged.
Parameters:
- path: absolute filesystem path to the accounts JSON file.
- label: the label of the account to remove.
Returns an error if the file cannot be loaded or saved.
Side effects: modifies the accounts file at path if the label is found.
func ResolveTokenCacheBackend ¶
ResolveTokenCacheBackend determines which token storage backend is actually in use at runtime based on the configured storage preference. This is the CGo-enabled build variant where the OS keychain is available.
Resolution logic mirrors InitCache:
- "file": returns "file" (file-based AES-256-GCM, keychain skipped).
- "keychain": returns "keychain" if the OS keychain probe succeeds, otherwise returns "file" (no fallback -- but the probe here is informational; the actual InitCache may have returned zero-value).
- "auto": returns "keychain" if the OS keychain probe succeeds, otherwise returns "file".
Parameters:
- name: the cache partition name (same value passed to InitCache).
- storage: the token storage backend preference ("auto", "keychain", or "file").
Returns "keychain" or "file".
func RestoreAccounts ¶
func RestoreAccounts( accountsPath string, cacheNameBase string, authRecordDir string, registry *AccountRegistry, credFactory CredentialFactory, clientFactory GraphClientFactory, scopes []string, tokenStorage string, ) (restored int, total int)
RestoreAccounts loads persisted account configurations and restores them into the account registry. For each account, it creates a credential via the provided CredentialFactory, attempts silent token acquisition with a bounded timeout, creates a Graph client, and registers the account in the registry.
Accounts that fail silent auth are still registered with a nil Graph client. The auth middleware handles re-authentication on first tool call.
If the accounts file does not exist, the function returns immediately with no error and zero restored accounts. Individual account failures are logged but do not prevent other accounts from being restored.
Restore is idempotent for labels already present in the registry (e.g. the "default" account registered at startup). Such entries are silently skipped at Debug level rather than producing a warning.
Parameters:
- accountsPath: filesystem path to the accounts JSON file.
- cacheNameBase: base name for the OS keychain partition. Each account appends its label as "{cacheNameBase}-{label}".
- authRecordDir: directory where per-account auth record files are stored.
- registry: the account registry to populate with restored accounts.
- credFactory: factory function to create credentials and authenticators.
- clientFactory: factory function to create Graph clients from credentials.
- scopes: OAuth scopes to use for silent token acquisition (from Scopes(cfg)).
- tokenStorage: token storage backend forwarded from the top-level server configuration so that per-account credentials honour the same storage preference as the default credential ("auto", "keychain", or "file").
Returns the number of successfully restored accounts (with active tokens) and the total number of accounts loaded from the file.
func SaveAccounts ¶
func SaveAccounts(path string, accounts []AccountConfig) error
SaveAccounts writes account configurations to the JSON file at the given path. The write is atomic: data is written to a temporary file in the same directory, then renamed to the target path. This prevents corruption from crashes during write.
Parameters:
- path: absolute filesystem path to the accounts JSON file.
- accounts: the account configurations to persist.
Returns an error if the file cannot be written.
Side effects: creates or overwrites the file at path. Creates the parent directory if it does not exist.
func SaveAuthRecord ¶
func SaveAuthRecord(path string, record azidentity.AuthenticationRecord) error
SaveAuthRecord serializes the AuthenticationRecord to JSON and writes it to the file at path. The parent directory is created with permissions 0700 if it does not exist. The file is written with permissions 0600 (owner read/write only).
Parameters:
- path: absolute filesystem path where the record will be saved.
- record: the AuthenticationRecord obtained from a successful authentication.
Returns an error if directory creation, JSON marshaling, or file writing fails.
Side effects: creates directories and writes a file to disk.
func Scopes ¶
Scopes returns the OAuth scope slice based on the application configuration. The calendar scope is always included. Mail scopes are selected according to configuration:
- When cfg.MailManageEnabled is true, mailReadWriteScope ("Mail.ReadWrite") is appended. This scope subsumes Mail.Read, so mailScope is not also added.
- Otherwise, when cfg.MailEnabled is true, mailScope ("Mail.Read") is appended.
- When both flags are false, no mail scope is requested.
Scopes never includes "Mail.Send"; sending mail is deliberately outside the server's capability surface.
Parameters:
- cfg: the application configuration providing MailEnabled and MailManageEnabled.
Returns the slice of OAuth scopes to request during authentication and Graph client initialization.
func UpdateAccountUPN ¶ added in v0.3.0
UpdateAccountUPN sets the UPN field for the account identified by label in the persistent accounts file. The file is loaded, the matching entry's UPN is replaced, and the file is saved atomically. If the label is not found, no error is returned and the file is left unchanged (callers can choose to treat this as a silent no-op migration path).
Parameters:
- path: absolute filesystem path to the accounts JSON file.
- label: label of the account whose UPN should be updated.
- upn: the User Principal Name to persist.
Returns an error if the file cannot be loaded or saved. Returns nil if the label is not found.
Side effects: rewrites the accounts file at path when the label matches.
func WithAccountAuth ¶
func WithAccountAuth(ctx context.Context, auth AccountAuth) context.Context
WithAccountAuth returns a new context with the given AccountAuth stored under accountAuthKey. The AccountResolver middleware calls this to inject the resolved account's authentication details into the request context.
Parameters:
- ctx: the parent context.
- auth: the account authentication details.
Returns a derived context containing the AccountAuth.
func WithAccountInfo ¶ added in v0.2.1
func WithAccountInfo(ctx context.Context, info AccountInfo) context.Context
WithAccountInfo returns a new context with the given AccountInfo stored under accountInfoKey. The AccountResolver middleware calls this after resolving the account to make label and email available to tool handlers.
Parameters:
- ctx: the parent context.
- info: the resolved account label and email.
Returns a derived context containing the AccountInfo.
func WithGraphClient ¶
func WithGraphClient(ctx context.Context, client *msgraphsdk.GraphServiceClient) context.Context
WithGraphClient returns a new context with the given Graph client stored under graphClientKey. The AccountResolver middleware calls this to inject the resolved account's client into the request context.
Parameters:
- ctx: the parent context.
- client: the Graph client for the resolved account.
Returns a derived context containing the client.
Types ¶
type AccountAuth ¶
type AccountAuth struct {
// Authenticator is the credential's Authenticator interface for triggering
// interactive re-authentication.
Authenticator Authenticator
// AuthRecordPath is the filesystem path for persisting this account's
// AuthenticationRecord.
AuthRecordPath string
// AuthMethod is the authentication method ("browser" or "device_code")
// that controls the re-authentication flow.
AuthMethod string
}
AccountAuth holds the authentication details for a resolved account. The AuthMiddleware uses these fields to perform per-account re-authentication when a tool call encounters an auth error.
func AccountAuthFromContext ¶
func AccountAuthFromContext(ctx context.Context) (AccountAuth, bool)
AccountAuthFromContext retrieves the AccountAuth previously stored via WithAccountAuth. The AuthMiddleware calls this to obtain per-account credentials for re-authentication.
Parameters:
- ctx: the context to retrieve the AccountAuth from.
Returns the AccountAuth and true if present, or a zero-value AccountAuth and false if not.
type AccountConfig ¶
type AccountConfig struct {
// Label is the unique human-readable identifier for this account.
Label string `json:"label"`
// ClientID is the OAuth 2.0 client (application) ID for this account's
// app registration.
ClientID string `json:"client_id"`
// TenantID is the Entra ID tenant identifier for this account
// (e.g., "common", "organizations", or a specific tenant GUID).
TenantID string `json:"tenant_id"`
// AuthMethod is the authentication method used for this account
// (e.g., "auth_code", "browser", "device_code").
AuthMethod string `json:"auth_method"`
// UPN is the User Principal Name (e.g., "alice@contoso.com") resolved
// from the Microsoft Graph /me endpoint after authentication. It serves
// as a stable, human-recognizable account identity that is persisted
// across restarts so the registry can populate AccountEntry.Email
// without a Graph API call at startup. Empty for accounts created
// before CR-0056 or before EnsureEmail has run; backfilled lazily.
UPN string `json:"upn"`
}
AccountConfig holds the identity configuration for a single account. These fields are persisted to the accounts JSON file and used to reconstruct credentials after a server restart.
func FindByIdentity ¶ added in v0.4.0
func FindByIdentity(accounts []AccountConfig, clientID, tenantID string) (AccountConfig, bool)
FindByIdentity searches accounts for the first entry whose ClientID and TenantID both match the supplied arguments. It is used by main.go at startup to determine whether the env-cfg identity is already covered by a named entry in accounts.json, so that the implicit "default" registration can be skipped.
Parameters:
- accounts: the account configurations to search.
- clientID: the OAuth 2.0 client ID to match.
- tenantID: the Entra ID tenant identifier to match.
Returns the first matching AccountConfig and true, or (AccountConfig{}, false) when no match is found. Empty clientID or tenantID arguments always return (AccountConfig{}, false) to prevent spurious matches against zero-value fields.
func LoadAccounts ¶
func LoadAccounts(path string) ([]AccountConfig, error)
LoadAccounts reads account configurations from the JSON file at the given path. If the file does not exist, an empty slice is returned with no error.
Parameters:
- path: absolute filesystem path to the accounts JSON file.
Returns the loaded account configurations, or an error if the file exists but cannot be read or parsed.
type AccountEntry ¶
type AccountEntry struct {
// Label is the unique human-readable identifier for this account
// (e.g., "work", "personal", "default").
Label string
// ClientID is the OAuth 2.0 client (application) ID used to authenticate
// this account. Stored for persistence so the account can be reconstructed
// after a server restart.
ClientID string
// TenantID is the Entra ID tenant identifier used to authenticate this
// account (e.g., "common", "organizations", or a specific tenant GUID).
// Stored for persistence so the account can be reconstructed after a
// server restart.
TenantID string
// AuthMethod is the authentication method used for this account
// (e.g., "auth_code", "browser", "device_code"). Stored for persistence
// so the account can be reconstructed after a server restart.
AuthMethod string
// Credential is the Azure token credential used by the Graph SDK to
// obtain access tokens for API calls.
Credential azcore.TokenCredential
// Authenticator is the credential's Authenticator interface for
// triggering interactive re-authentication when tokens expire.
Authenticator Authenticator
// Client is the Microsoft Graph SDK client configured with this
// account's credential.
Client *msgraphsdk.GraphServiceClient
// AuthRecordPath is the filesystem path where this account's
// AuthenticationRecord is persisted.
AuthRecordPath string
// CacheName is the OS keychain partition name for this account's
// persistent token cache.
CacheName string
// Authenticated indicates whether this account has a valid credential
// and Graph client. Accounts restored from disk without a cached token
// may have Authenticated == false until the user re-authenticates.
Authenticated bool
// Email is the authenticated user's email address, lazily fetched from the
// Microsoft Graph /me endpoint by EnsureEmail. Empty until first fetch.
Email string
// contains filtered or unexported fields
}
AccountEntry holds all state for a single authenticated account in the registry. Each field is populated during account creation (add_account tool or startup registration of the default account).
type AccountInfo ¶ added in v0.2.1
type AccountInfo struct {
// Label is the unique account identifier (e.g., "default", "work").
Label string
// Email is the authenticated user's email address fetched from /me.
// Empty when EnsureEmail has not yet run successfully for this account.
Email string
// Advisory is an optional human-readable note produced during account
// resolution — for example, when the resolver auto-selects the sole
// authenticated account while disconnected siblings also exist. Downstream
// response formatters surface this string so the LLM and the user see the
// broader account landscape rather than silently using one account.
// Empty when no advisory applies.
Advisory string
}
AccountInfo holds the label and email of the account resolved for a request. Email may be empty if the /me fetch has not yet completed for this account.
func AccountInfoFromContext ¶ added in v0.2.1
func AccountInfoFromContext(ctx context.Context) (AccountInfo, bool)
AccountInfoFromContext retrieves the AccountInfo previously stored via WithAccountInfo. Tool handlers call this to obtain the account label and email for inclusion in response text.
Parameters:
- ctx: the context to retrieve the AccountInfo from.
Returns the AccountInfo and true if present, or a zero-value AccountInfo and false if not.
type AccountRegistry ¶
type AccountRegistry struct {
// contains filtered or unexported fields
}
AccountRegistry is a thread-safe store for multiple authenticated accounts. It uses a sync.RWMutex to allow concurrent reads while serializing writes.
func NewAccountRegistry ¶
func NewAccountRegistry() *AccountRegistry
NewAccountRegistry creates an empty AccountRegistry ready for use.
Returns a new AccountRegistry with an initialized internal map.
func (*AccountRegistry) Add ¶
func (r *AccountRegistry) Add(entry *AccountEntry) error
Add registers a new account entry in the registry. The entry's Label must be non-empty, match the pattern ^[a-zA-Z0-9_-]{1,64}$, and not already exist in the registry.
Parameters:
- entry: the account entry to register. Must have a valid, unique Label.
Returns an error if the label is invalid or already registered.
Side effects: stores the entry in the registry under its Label.
func (*AccountRegistry) Count ¶
func (r *AccountRegistry) Count() int
Count returns the number of registered accounts.
func (*AccountRegistry) Get ¶
func (r *AccountRegistry) Get(label string) (*AccountEntry, bool)
Get retrieves an account entry by label.
Parameters:
- label: the label of the account to retrieve.
Returns the entry and true if found, or nil and false if not.
func (*AccountRegistry) GetByUPN ¶ added in v0.3.0
func (r *AccountRegistry) GetByUPN(upn string) (*AccountEntry, bool)
GetByUPN retrieves an account entry by its User Principal Name (UPN), matched against the entry's Email field using case-insensitive comparison. This supports CR-0056 dual lookup where a tool's `account` parameter may carry either a label or a UPN.
Parameters:
- upn: the user principal name to look up (e.g., "alice@contoso.com").
Returns the matching entry and true on success, or nil and false when no entry has a matching Email. An empty upn argument never matches.
func (*AccountRegistry) Labels ¶
func (r *AccountRegistry) Labels() []string
Labels returns a sorted list of all registered account labels.
Returns a slice of label strings in alphabetical order.
func (*AccountRegistry) List ¶
func (r *AccountRegistry) List() []*AccountEntry
List returns all registered account entries sorted alphabetically by label.
Returns a slice of account entries. The returned slice is a copy; modifying it does not affect the registry.
func (*AccountRegistry) ListAuthenticated ¶
func (r *AccountRegistry) ListAuthenticated() []*AccountEntry
ListAuthenticated returns all registered account entries that have Authenticated == true, sorted alphabetically by label.
Returns a slice of authenticated account entries. The returned slice is a copy; modifying it does not affect the registry.
func (*AccountRegistry) Remove ¶
func (r *AccountRegistry) Remove(label string) error
Remove deletes an account from the registry by label. Any registered label may be removed, including "default"; CR-0056 FR-44/FR-45 require removal to succeed regardless of connection state and to leave a clean zero-account state when the last account is removed.
Parameters:
- label: the label of the account to remove.
Returns an error if no account with the given label exists.
Side effects: removes the entry from the registry.
func (*AccountRegistry) Update ¶ added in v0.3.0
func (r *AccountRegistry) Update(label string, fn func(*AccountEntry)) error
Update applies the provided function to the account entry identified by label while holding the registry's write lock. The function may mutate any field on the entry (for example to flip Authenticated, swap the Client, or refresh the Email). Update ensures state transitions cannot race against concurrent registry reads.
Parameters:
- label: label of the entry to modify.
- fn: callback invoked with the live entry pointer; must not be nil.
Returns an error if the label is not found or fn is nil.
Side effects: invokes fn while holding the registry's write lock; any mutation fn performs becomes visible to subsequent registry readers.
type AccountsFile ¶
type AccountsFile struct {
// Accounts is the list of persisted account configurations.
Accounts []AccountConfig `json:"accounts"`
}
AccountsFile is the top-level structure of the persistent accounts JSON file. It wraps a slice of AccountConfig entries.
type AuthCodeCredential ¶
type AuthCodeCredential struct {
// contains filtered or unexported fields
}
AuthCodeCredential wraps MSAL Go's public.Client to implement the OAuth 2.0 authorization code flow with PKCE using the nativeclient redirect URI. It satisfies both azcore.TokenCredential (for the Graph SDK) and Authenticator (for the AuthMiddleware), as well as AuthCodeFlow (for the add_account tool and complete_auth tool).
The credential lifecycle is:
- AuthCodeURL generates the authorization URL for the user.
- The user authenticates in their browser and copies the redirect URL.
- ExchangeCode exchanges the authorization code for tokens.
- GetToken returns cached tokens via AcquireTokenSilent.
Thread safety: AuthCodeCredential is safe for concurrent use. The MSAL public.Client is itself thread-safe; the credential adds a sync.RWMutex to protect the cached account field.
func NewAuthCodeCredential ¶
func NewAuthCodeCredential(clientID, tenantID string, opts ...NewAuthCodeCredentialOption) (*AuthCodeCredential, error)
NewAuthCodeCredential constructs an AuthCodeCredential wrapping a new MSAL public.Client configured with the specified client ID and tenant ID.
Parameters:
- clientID: the OAuth 2.0 application (client) ID.
- tenantID: the Entra ID tenant identifier (e.g., "common" or a GUID).
- opts: functional options for configuring cache and other settings.
Returns the constructed AuthCodeCredential, or an error if the MSAL public.Client cannot be created.
func (*AuthCodeCredential) Account ¶
func (c *AuthCodeCredential) Account() (public.Account, bool)
Account returns the cached MSAL account and whether one has been set. This is used by Phase 2 account persistence to save the account to disk after successful authentication.
Returns the cached account and true if an account has been set, or a zero-value account and false otherwise.
func (*AuthCodeCredential) AuthCodeURL ¶
AuthCodeURL returns the authorization URL for the user to visit in their browser. The URL includes PKCE code_challenge and code_challenge_method=S256 parameters. A new PKCE code verifier is generated on each call and stored for use by the subsequent ExchangeCode call.
Parameters:
- ctx: context for the operation.
- scopes: OAuth scopes to request (e.g., "Calendars.ReadWrite").
Returns the authorization URL string, or an error if URL construction or PKCE generation fails.
func (*AuthCodeCredential) Authenticate ¶
func (c *AuthCodeCredential) Authenticate(_ context.Context, _ *policy.TokenRequestOptions) (azidentity.AuthenticationRecord, error)
Authenticate is provided for compatibility with the Authenticator interface used by the AuthMiddleware. For the auth_code method, actual authentication is driven by the AuthCodeFlow interface (AuthCodeURL + ExchangeCode) rather than this method. Authenticate returns an empty AuthenticationRecord and an error indicating that the auth_code flow must be used instead.
Parameters:
- ctx: context for the authentication call.
- opts: token request options (unused for auth_code).
Returns a zero-value AuthenticationRecord and an error.
func (*AuthCodeCredential) ExchangeCode ¶
func (c *AuthCodeCredential) ExchangeCode(ctx context.Context, redirectURL string, scopes []string) error
ExchangeCode extracts the authorization code from the redirect URL and exchanges it for tokens via MSAL Go's AcquireTokenByAuthCode. On success, the resulting MSAL account is stored for subsequent silent token acquisition.
Parameters:
- ctx: context for the token exchange network call.
- redirectURL: the full URL from the browser's address bar after authentication, which must start with the nativeclient redirect URI.
- scopes: OAuth scopes to request.
Returns an error if the URL does not start with the nativeclient redirect URI, does not contain a "code" query parameter, is malformed, or if the token exchange fails.
Side effects: stores the MSAL account on success.
func (*AuthCodeCredential) GetToken ¶
func (c *AuthCodeCredential) GetToken(ctx context.Context, options policy.TokenRequestOptions) (azcore.AccessToken, error)
GetToken acquires an access token for the requested scopes. It first attempts silent acquisition using the cached MSAL account. If no account is cached or silent acquisition fails, it returns an error that the AuthMiddleware recognizes as an authentication error, triggering the interactive auth code flow.
Parameters:
- ctx: context for the token acquisition call.
- options: token request options specifying scopes.
Returns an azcore.AccessToken on success, or an error when authentication is required.
GetToken implements azcore.TokenCredential.
func (*AuthCodeCredential) LoadPersistedAccount ¶
func (c *AuthCodeCredential) LoadPersistedAccount(path string) error
LoadPersistedAccount loads a previously persisted MSAL account from disk and sets it on the credential for silent token acquisition. If the file does not exist or contains invalid data, the credential remains without a cached account (requiring fresh authentication).
Parameters:
- path: absolute filesystem path to the persisted account JSON file.
Returns an error only for unexpected I/O failures. Missing or corrupt files are handled gracefully.
Side effects: sets the credential's cached account on success.
func (*AuthCodeCredential) PersistAccount ¶
func (c *AuthCodeCredential) PersistAccount(path string) error
PersistAccount saves the credential's current MSAL account to disk for restoration on future runs. If no account has been set (i.e., authentication has not completed), this is a no-op.
Parameters:
- path: absolute filesystem path where the account will be saved.
Returns an error if the account cannot be written to disk.
Side effects: writes the account to disk.
func (*AuthCodeCredential) SetAccount ¶
func (c *AuthCodeCredential) SetAccount(account public.Account)
SetAccount sets the cached MSAL account for silent token acquisition. This is used by Phase 2 account persistence to restore the account from disk on startup without requiring re-authentication.
Parameters:
- account: the MSAL account to cache.
type AuthCodeFlow ¶
type AuthCodeFlow interface {
// AuthCodeURL returns the authorization URL for the user to visit in
// their browser. The URL includes PKCE code_challenge parameters
// generated internally by MSAL Go.
//
// Parameters:
// - ctx: context for the operation.
// - scopes: OAuth scopes to request (e.g., "Calendars.ReadWrite").
//
// Returns the authorization URL string, or an error if URL construction
// fails.
AuthCodeURL(ctx context.Context, scopes []string) (string, error)
// ExchangeCode extracts the authorization code from the redirect URL and
// exchanges it for tokens via MSAL Go's AcquireTokenByAuthCode.
//
// Parameters:
// - ctx: context for the token exchange network call.
// - redirectURL: the full URL from the browser's address bar after
// authentication, starting with the nativeclient redirect URI.
// - scopes: OAuth scopes to request.
//
// Returns an error if the URL is invalid, the code is missing, or the
// token exchange fails.
ExchangeCode(ctx context.Context, redirectURL string, scopes []string) error
}
AuthCodeFlow is the interface for credentials that support the manual authorization code flow. AuthCodeCredential implements this interface. The middleware and add_account tool use this interface to drive the auth code flow without concrete type assertions against AuthCodeCredential.
type Authenticator ¶
type Authenticator interface {
// Authenticate performs interactive authentication and returns an
// AuthenticationRecord containing non-secret account metadata that
// enables silent token acquisition on future runs.
//
// Parameters:
// - ctx: context for the authentication call. Should have a generous
// timeout since interactive authentication requires user action.
// - opts: token request options specifying scopes and CAE enablement.
//
// Returns the AuthenticationRecord on success, or an error if the
// interactive authentication flow fails or times out.
Authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (azidentity.AuthenticationRecord, error)
}
Authenticator is the interface for performing explicit authentication and obtaining an AuthenticationRecord. Both *azidentity.DeviceCodeCredential and *azidentity.InteractiveBrowserCredential satisfy this interface implicitly via structural typing. The middleware uses this interface to trigger re-authentication when a cached token expires, without coupling to a specific credential type.
This follows the Interface Segregation Principle: a single-method interface capturing only the Authenticate capability needed by the middleware, separate from the azcore.TokenCredential interface used by the Graph SDK.
func SetupCredential ¶
func SetupCredential(cfg config.Config) (azcore.TokenCredential, Authenticator, error)
SetupCredential constructs an Azure Identity credential configured with a persistent token cache, an authentication record loaded from disk, and the application's client and tenant IDs. The credential type is selected based on cfg.AuthMethod:
- "auth_code": constructs an AuthCodeCredential that implements the manual authorization code flow with PKCE using the nativeclient redirect URI. Uses MSAL Go's public.Client for token acquisition.
- "browser": constructs an InteractiveBrowserCredential that opens the system browser for OAuth login via the authorization code flow with PKCE. The RedirectURL is set to "http://localhost" as required by the app registration.
- "device_code": constructs a DeviceCodeCredential with a context-aware UserPrompt callback that sends the device code message as an MCP notification or falls back to stderr.
Authentication is deferred to the first tool call rather than blocking at startup.
Parameters:
- cfg: the application configuration providing AuthMethod, ClientID, TenantID, AuthRecordPath, and CacheName.
Returns the credential as both azcore.TokenCredential (for the Graph SDK) and Authenticator (for the middleware), or an error if credential construction fails. The credential does not hold a token until GetToken is called (lazily by the Graph SDK on the first API call).
Side effects: initializes the OS keychain token cache, reads the auth record from disk.
func SetupCredentialForAccount ¶
func SetupCredentialForAccount(label, clientID, tenantID, authMethod, cacheNameBase, authRecordDir, tokenStorage string) (azcore.TokenCredential, Authenticator, string, string, error)
SetupCredentialForAccount constructs an Azure Identity credential for a specific account, using per-account token cache partitioning and a dedicated auth record path. This is the multi-account counterpart to SetupCredential, used by the add_account tool to create credentials dynamically at runtime.
The caller is responsible for providing non-empty clientID, tenantID, and authMethod values. The add_account handler resolves defaults from the server config before calling this function.
Parameters:
- label: the unique account label, used to derive the cache partition and auth record filename.
- clientID: the OAuth 2.0 client (application) ID. Must be non-empty.
- tenantID: the Entra ID tenant identifier. Must be non-empty.
- authMethod: the authentication method ("auth_code", "browser", or "device_code"). Must be non-empty.
- cacheNameBase: the base name for the OS keychain partition. The account label is appended as "{cacheNameBase}-{label}".
- authRecordDir: the directory where auth record files are stored. The per-account file is named "{label}_auth_record.json" within this directory.
- tokenStorage: the token storage backend ("auto", "keychain", or "file"), forwarded from the top-level server configuration so that per-account credentials honour the same storage preference as the default credential. An empty string falls through to the "auto" behaviour in InitCache.
Returns the credential as azcore.TokenCredential, the Authenticator interface, the full auth record path, and the cache name. Returns an error if the auth method is unsupported or credential construction fails.
Side effects: initializes the token cache (OS keychain or file-based depending on tokenStorage), reads the auth record from disk if present.
type CredentialFactory ¶
type CredentialFactory func( label, clientID, tenantID, authMethod, cacheNameBase, authRecordDir, tokenStorage string, ) (azcore.TokenCredential, Authenticator, string, string, error)
CredentialFactory creates a credential and authenticator for an account. It encapsulates the setup logic (cache partition, auth record path, SDK credential construction) behind a function type so that tests can inject mock credentials without triggering real Azure SDK authentication flows.
The signature matches SetupCredentialForAccount exactly, allowing direct assignment: var factory CredentialFactory = SetupCredentialForAccount.
Parameters:
- label: the unique account label.
- clientID: the OAuth client ID.
- tenantID: the Entra ID tenant ID.
- authMethod: the authentication method (browser, device_code, auth_code).
- cacheNameBase: base name for the OS keychain partition.
- authRecordDir: directory where per-account auth record files are stored.
- tokenStorage: token storage backend ("auto", "keychain", or "file"), forwarded from the top-level server configuration so that per-account credentials honour the same storage preference as the default credential.
Returns the token credential, authenticator, auth record path, cache name, or an error if credential construction fails.
type GraphClientFactory ¶
type GraphClientFactory func(cred azcore.TokenCredential) (*msgraphsdk.GraphServiceClient, error)
GraphClientFactory creates a Graph API client from a token credential. This function type allows test injection of a mock factory that returns a pre-built client without real Azure SDK interaction.
func NewDefaultGraphClientFactory ¶
func NewDefaultGraphClientFactory(scopes []string) GraphClientFactory
NewDefaultGraphClientFactory returns a GraphClientFactory that creates a GraphServiceClient using the provided credential with the given OAuth scopes.
Parameters:
- scopes: OAuth scopes to pass to the Graph SDK client (from Scopes(cfg)).
Returns a factory function that creates Graph clients with the specified scopes.
type NewAuthCodeCredentialOption ¶
type NewAuthCodeCredentialOption func(*authCodeCredentialOptions)
NewAuthCodeCredentialOption is a functional option for NewAuthCodeCredential.
func WithCacheAccessor ¶
func WithCacheAccessor(cacheAccessor msalcache.ExportReplace) NewAuthCodeCredentialOption
WithCacheAccessor returns a NewAuthCodeCredentialOption that configures the MSAL public.Client with a persistent token cache accessor. The accessor must implement the MSAL cache.ExportReplace interface. Use InitMSALCache to create a suitable accessor backed by OS keychain storage.
Parameters:
- accessor: the MSAL-compatible cache accessor for persistent token storage.