{"modulePath":"github.com/LeanerCloud/cloud-commitments-platform","version":"v0.0.0-20261202160902-a99bcb5bfea3","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package api\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for analytics endpoints.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\nPackage api provides the HTTP API handlers for the CUDly dashboard.\n\n## Constants\n\n```go\nconst (\n\t// DefaultRecommendationsPageSize is the page size used when a caller\n\t// sends a cursor without a limit.\n\tDefaultRecommendationsPageSize = 500\n\n\t// MaxRecommendationsPageSize caps the row count of one page. It is an\n\t// upper bound only: recommendationsPageByteBudget can cut a page shorter.\n\tMaxRecommendationsPageSize = 1000\n)\n```\nOpt-in cursor pagination for GET /api/recommendations (refs issue #723).\n\nThe list endpoint used to return the whole filtered cache in one body, which passes the 6 MB Lambda response cap once a tenant accumulates a few thousand recommendations. A caller that sends \\`limit\\` (and, for later pages, the \\`cursor\\` returned as \\`next\\_cursor\\`) gets one bounded page. A paginated request reads only the page (plus one row) from the store, with the summary totaled by an SQL aggregate (issue #981, see handler\\_recommendations\\_scan.go). A page is bounded twice: by row count (limit) and by serialized bytes (recommendationsPageByteBudget), because the opaque Details blob makes the size of a row data-dependent. A request carrying neither parameter keeps the existing unpaginated shape unchanged, so the current frontend (which sorts, groups and totals the full set client-side) keeps working until it adopts pagination.\n\nIn both modes \\`summary\\` and \\`regions\\` describe the full filtered set, not just the returned page, so headline totals stay correct while paging.\n\n```go\nconst AzureRevocationWindowDays = config.AzureRevocationWindowDays\n```\nAzureRevocationWindowDays is the number of days after purchase within which Azure reservations are eligible for a return (refund). Per Azure docs: [https://learn.microsoft.com/azure/cost-management-billing/reservations/exchange-and-refund-azure-reservations](https://learn.microsoft.com/azure/cost-management-billing/reservations/exchange-and-refund-azure-reservations) Aliases config.AzureRevocationWindowDays so the purchase-write path and this endpoint share a single source of truth for the window length.\n\n```go\nconst HSTSHeaderValue = \"max-age=31536000; includeSubDomains; preload\"\n```\nsetSecurityHeaders adds comprehensive security headers to the response. HSTSHeaderValue is the Strict-Transport-Security value for every response path: API responses here, and the HTTP-mode static, Lambda static and health responses in internal/server. One constant keeps the modes from drifting apart again (issue #14: Lambda mode had dropped \"preload\"). \"preload\" only makes the domain eligible for the browser preload list; submitting it to hstspreload.org is a separate, manual step.\n\n```go\nconst MaxAccountIDsPerRequest = 200\n```\nMaxAccountIDsPerRequest caps the number of account IDs accepted in a single comma-separated \\`account\\_ids\\` query parameter. Each accepted ID fans out into per-account DB queries / cloud API calls downstream, so an unbounded list is an amplification vector — a single request with thousands of IDs can exhaust connection pools or hit cloud-API rate limits. 200 is generous for legitimate usage (typical operators have far fewer onboarded accounts) while keeping the worst-case work bounded.\n\n```go\nconst MaxHistoryDateRangeDays = 366\n```\nMaxHistoryDateRangeDays caps the inclusive start/end window the History handler accepts on a single request. Mirrors the analytics cap (issue #414 / PR #529): an unbounded range turns the WHERE-on-timestamp into a full-table scan over purchase\\_history, which the dashboard frontend neither needs nor renders coherently past a year. 366 admits a full leap year and rejects anything larger with 400.\n\n```go\nconst (\n\t// MaxRequestBodySize is the maximum allowed request body size (1MB).\n\tMaxRequestBodySize = 1 * 1024 * 1024\n)\n```\nSecurity constants.\n\n```go\nconst (\n\t// OIDCBasePath is the URL prefix CUDly publishes its OIDC issuer\n\t// under. Federated credentials registered with target clouds\n\t// (Azure AD, GCP STS) must use issuer = \u003cbase URL\u003e + OIDCBasePath.\n\tOIDCBasePath = \"/oidc\"\n)\n```\nOIDC discovery paths served by this handler. Scoped under /oidc/ so the paths read descriptively in code and in CUDly's URL space rather than sitting at the root under the opaque .well-known prefix. The RFC 8414 discovery suffix still applies (Azure AD, GCP STS, etc. fetch ${issuer}/.well-known/openid-configuration), but because we register the issuer URL as \\\u003chost\u003e/oidc the full external paths become \\\u003chost\u003e/oidc/.well-known/openid-configuration — the issuer prefix alone appears in routing lists, the well-known suffix is only an implementation detail inside handler\\_oidc.go.\n\n## Variables\n\n```go\nvar ErrRateLimiterUnavailable = errors.New(\"rate limiter has no database pool\")\n```\nErrRateLimiterUnavailable is returned by a DBRateLimiter that has no database pool. It cannot count attempts, so it reports an error instead of allowing: checkRateLimitStrict then answers 503 on the credential endpoints rather than silently dropping their brute-force protection (issue #104).\n\n## Functions\n\n```go\nfunc IsClientError(err error) (*clientError, bool)\n```\nIsClientError checks if the error is a client error and returns it.\n\n```go\nfunc IsNotFoundError(err error) bool\n```\nIsNotFoundError checks if the error is a not found error.\n\n```go\nfunc IsOIDCIssuerPath(path string) bool\n```\nIsOIDCIssuerPath returns true if path belongs to CUDly's OIDC issuer surface (the discovery document or the JWKS). The server transport layer uses this to route requests directly to HandleOIDC before the main API router so the issuer endpoints never touch the auth middleware or the static-file fallback.\n\n```go\nfunc NewClientError(code int, message string) error\n```\nNewClientError creates a new client-facing error with the given HTTP status code and message.\n\n```go\nfunc NewClientErrorWithDetails(code int, message string, details map[string]any) error\n```\nNewClientErrorWithDetails creates a client-facing error that also carries structured detail fields. The response writer flattens those into the JSON body so consumers can branch on machine-readable hints rather than substring-matching the message. Used by the retry handler (issue #47) for ops\\_hint + retry\\_attempt\\_n / threshold callouts. The details map is copied at construction so caller mutations after the error is created don't leak into the response body.\n\n```go\nfunc NewClientErrorWithHeaders(code int, message string, details map[string]any, headers map[string]string) error\n```\nNewClientErrorWithHeaders is NewClientErrorWithDetails plus extra response headers (for example Retry-After). Both maps are copied at construction.\n\n```go\nfunc OfferedInstanceTypes(ctx context.Context, region string, fetch func(context.Context) ([]string, error)) []string\n```\nOfferedInstanceTypes returns the EC2 instance types offered in region, for exchange.WithOfferedInstanceTypes and RunAutoExchangeParams.OfferedInstanceTypes. fetch is normally ec2svc.Client.GetValidResourceTypes (DescribeInstanceTypeOfferings).\n\nOn a fetch error or an empty catalog it logs a warning naming the region and returns nil, so reshape analysis proceeds on the legacy size ladder instead of failing the request. Nothing is cached, so the next call queries the catalog again rather than reusing the fallback.\n\n## Types\n\n```go\ntype APIKeyInfo struct {\n\tID          string       `json:\"id\"`\n\tName        string       `json:\"name\"`\n\tKeyPrefix   string       `json:\"key_prefix\"`\n\tExpiresAt   string       `json:\"expires_at,omitempty\"`\n\tCreatedAt   string       `json:\"created_at\"`\n\tLastUsedAt  string       `json:\"last_used_at,omitempty\"`\n\tPermissions []Permission `json:\"permissions,omitempty\"`\n\tIsActive    bool         `json:\"is_active\"`\n}\n```\nAPIKeyInfo represents public information about an API key.\n\n```go\ntype AccountServiceOverrideRequest struct {\n\tEnabled        *bool    `json:\"enabled,omitempty\"`\n\tTerm           *int     `json:\"term,omitempty\"`\n\tPayment        *string  `json:\"payment,omitempty\"`\n\tCoverage       *float64 `json:\"coverage,omitempty\"`\n\tRampSchedule   *string  `json:\"ramp_schedule,omitempty\"`\n\tIncludeEngines []string `json:\"include_engines,omitempty\"`\n\tExcludeEngines []string `json:\"exclude_engines,omitempty\"`\n\tIncludeRegions []string `json:\"include_regions,omitempty\"`\n\tExcludeRegions []string `json:\"exclude_regions,omitempty\"`\n\tIncludeTypes   []string `json:\"include_types,omitempty\"`\n\tExcludeTypes   []string `json:\"exclude_types,omitempty\"`\n}\n```\nAccountServiceOverrideRequest is the request body for service override endpoints.\n\n```go\ntype AccountSummary struct {\n\tID         string `json:\"id\"`\n\tName       string `json:\"name\"`\n\tExternalID string `json:\"external_id\"`\n\tProvider   string `json:\"provider\"`\n}\n```\nAccountSummary is the minimal-disclosure projection of a cloud account used by the global topbar filter and the create-plan-from-commitment target prefill (issues #949, #951). It deliberately omits every credential/config field (role ARNs, subscription IDs, client emails, auth modes, bastion IDs, the self-account marker) so the endpoint can be gated on a low read verb that Standard / Read-Only users already hold, without leaking sensitive account configuration. The full CloudAccount object stays behind GET /api/accounts (view:accounts, admin-grade).\n\n```go\ntype AccountTestResult struct {\n\tMessage string `json:\"message\"`\n\tOK      bool   `json:\"ok\"`\n}\n```\nAccountTestResult is the response for the test-credentials endpoint.\n\n```go\ntype AdminExistsResponse struct {\n\tAdminExists bool `json:\"admin_exists\"`\n}\n```\nAdminExistsResponse holds the admin exists check response.\n\n```go\ntype AnalyticsClientInterface interface {\n\tQueryHistory(ctx context.Context, accountUUIDs []string, accountExternalIDsByProvider map[string][]string, provider string, start, end time.Time, interval string) ([]HistoryDataPoint, *HistorySummary, error)\n\tQueryBreakdown(ctx context.Context, accountUUIDs []string, accountExternalIDsByProvider map[string][]string, start, end time.Time, dimension string) (map[string]BreakdownValue, error)\n}\n```\nAnalyticsClientInterface defines the interface for analytics queries.\n\naccountUUIDs / accountExternalIDsByProvider are the dual-column account filter: rows match when cloud\\_account\\_id = ANY(accountUUIDs) OR (provider = p AND account\\_id = ANY(accountExternalIDsByProvider\\[p])). Both nil/empty means \"all accounts accessible to the caller\" (scoping is enforced upstream in the handler). The handler resolves the requested account (a top-bar chip UUID) into both representations via resolveSingleAccountFilterIDs so rows that carry only the external account\\_id (cloud\\_account\\_id NULL) are still aggregated, and the external ids stay grouped by provider so a reused external number across providers cannot leak the wrong rows (issue #701/#498/#866).\n\n```go\ntype AnalyticsCollectorInterface interface {\n\tCollect(ctx context.Context) error\n}\n```\nAnalyticsCollectorInterface defines the interface for analytics collection.\n\n```go\ntype AnalyticsResponse struct {\n\tStart      string             `json:\"start\"`\n\tEnd        string             `json:\"end\"`\n\tInterval   string             `json:\"interval\"`\n\tSummary    *HistorySummary    `json:\"summary\"`\n\tDataPoints []HistoryDataPoint `json:\"data_points\"`\n}\n```\nAnalyticsResponse represents the response for the analytics endpoint.\n\n```go\ntype AnalyticsSnapshotStoreInterface interface {\n\tQuerySavings(ctx context.Context, req analytics.QueryRequest) ([]analytics.SavingsSnapshot, error)\n\tQueryMonthlyTotals(ctx context.Context, accountUUIDs []string, accountExternalIDsByProvider map[string][]string, months int) ([]analytics.MonthlySummary, error)\n\tQueryByProvider(ctx context.Context, accountUUIDs []string, accountExternalIDsByProvider map[string][]string, startDate, endDate time.Time) ([]analytics.ProviderBreakdown, error)\n\tQueryByService(ctx context.Context, accountUUIDs []string, accountExternalIDsByProvider map[string][]string, provider string, startDate, endDate time.Time) ([]analytics.ServiceBreakdown, error)\n}\n```\nAnalyticsSnapshotStoreInterface exposes the savings-snapshot time-series for the /api/analytics/trends endpoint. It is the read side of the now-wired internal/analytics collector. Scoping is the dual-column model: the handler resolves the requested account into accountUUIDs + accountExternalIDsByProvider (see resolveSingleAccountFilterIDs) and the store ORs both columns so rows carrying only one identifier are still matched. Both empty means \"all\" — the handler MUST enforce allowed\\_accounts scope before passing empty filters.\n\n```go\ntype AuthLevel int\n```\nAuthLevel controls how Router.Route() enforces authentication. The Auth field on Route is MANDATORY — NewRouter panics at startup if any registered route leaves it at the zero value. See the const block below for the AuthAdmin / AuthUser / AuthPublic options.\n\nRouter.Route enforces these levels itself as a defense-in-depth check, in addition to the authentication middleware that runs earlier in the request pipeline. If middleware ordering ever changes or a new route bypasses validateSecurityContext, the router-level enforcement still rejects unauthorized requests.\n\n```go\nconst (\n\n\t// AuthAdmin requires admin role (admin API key or admin bearer-token\n\t// session). Enforced by Router.Route via h.requireAdmin.\n\tAuthAdmin AuthLevel\n\t// AuthUser requires any authenticated user (admin API key, user API\n\t// key, or any valid bearer-token session). Use for read-only views\n\t// and self-service endpoints (logout, profile, API key management).\n\t// Enforced by Router.Route via h.requireAuth.\n\tAuthUser\n\t// AuthPublic requires no authentication. Must also be listed in\n\t// isPublicEndpoint() so the middleware skips its auth/CSRF checks.\n\tAuthPublic\n)\n```\n\n```go\ntype AuthServiceInterface interface {\n\tLogin(ctx context.Context, req LoginRequest) (*LoginResponse, error)\n\tLogout(ctx context.Context, token string) error\n\tValidateSession(ctx context.Context, token string) (*Session, error)\n\tValidateCSRFToken(ctx context.Context, sessionToken, csrfToken string) error\n\tSetupAdmin(ctx context.Context, req SetupAdminRequest) (*LoginResponse, error)\n\tCheckAdminExists(ctx context.Context) (bool, error)\n\tRequestPasswordReset(ctx context.Context, email string) error\n\tConfirmPasswordReset(ctx context.Context, req PasswordResetConfirm) error\n\t// ResetTokenStatus returns the runtime state of a reset token\n\t// without consuming it. Used by the GET /api/auth/reset-password/\n\t// status endpoint so the frontend can branch on expired / used\n\t// tokens before rendering the reset-password form (issues #460,\n\t// #461). state is one of \"valid\" | \"expired\" | \"used\"; flow is\n\t// \"reset\" | \"invite\".\n\tResetTokenStatus(ctx context.Context, token string) (state string, flow string, err error)\n\tGetUser(ctx context.Context, userID string) (*User, error)\n\tUpdateUserProfile(ctx context.Context, userID string, email string, currentPassword string, newPassword string) error\n\t// User management - uses auth.API* types\n\tCreateUserAPI(ctx context.Context, actorUserID string, req auth.APICreateUserRequest) (*auth.APICreateUserResponse, error)\n\tUpdateUserAPI(ctx context.Context, actorUserID, userID string, req auth.APIUpdateUserRequest) (*auth.APIUser, error)\n\tDeleteUser(ctx context.Context, userID string) error\n\tListUsersAPI(ctx context.Context) (any, error)\n\tChangePasswordAPI(ctx context.Context, userID, currentPassword, newPassword string) error\n\t// MFA lifecycle (issue #497). All four require the user to be\n\t// already authenticated; setup + disable additionally require a\n\t// fresh password re-verify carried in the request body.\n\tMFASetupAPI(ctx context.Context, userID, password string) (secret, provisioningURI string, err error)\n\tMFAEnableAPI(ctx context.Context, userID, code string) (recoveryCodes []string, err error)\n\tMFADisableAPI(ctx context.Context, userID, password, codeOrRecovery string) error\n\tMFARegenerateRecoveryCodesAPI(ctx context.Context, userID, code string) (recoveryCodes []string, err error)\n\t// Group management - uses auth.API* types\n\t// CreateGroupAPI / UpdateGroupAPI take the acting principal so the\n\t// service can enforce the grant ceiling: a caller may not write a\n\t// permission onto a group that their own effective permissions do not\n\t// hold, and the money verbs carved out of admin:* are not grantable at\n\t// all (issues #1550, #1629).\n\tCreateGroupAPI(ctx context.Context, actorUserID string, req auth.APICreateGroupRequest) (*auth.APIGroup, error)\n\tUpdateGroupAPI(ctx context.Context, actorUserID, groupID string, req auth.APIUpdateGroupRequest) (*auth.APIGroup, error)\n\tDeleteGroup(ctx context.Context, groupID string) error\n\tGetGroupAPI(ctx context.Context, groupID string) (any, error)\n\tListGroupsAPI(ctx context.Context) (any, error)\n\t// Permission checking\n\tHasPermissionAPI(ctx context.Context, userID, action, resource string) (bool, error)\n\t// HasPermissionForConstraintsAPI checks action on resource against\n\t// request-derived constraint sets so per-permission Constraints\n\t// (MaxPurchaseAmount, Providers, Services, Regions, AccountIDs) are\n\t// enforced at execution time. Every constraint set must be granted by\n\t// at least one of the user's permissions (SEC-01, issue #1141).\n\tHasPermissionForConstraintsAPI(ctx context.Context, userID, action, resource string, constraintSets []auth.PermissionConstraints) (bool, error)\n\t// GetUserPermissionsAPI returns the effective permission set for a user\n\t// (union of all group permissions). Used by GET /api/auth/me/permissions.\n\t// Returns []auth.APIPermission converted to []PermissionEntry by the handler.\n\tGetUserPermissionsAPI(ctx context.Context, userID string) (any, error)\n\t// GetAPIKeyEffectivePermissionsAPI returns a user API key's effective\n\t// permission set (the key's permissions intersected with its owner's,\n\t// carrying the key's constraints): the set HasAPIKeyPermissionAPI\n\t// enforces. Used by GET /api/auth/me/permissions for user-API-key\n\t// principals so the key, not its owner, is described (issue #62). A\n\t// non-nil error means the key or its owner could not be confirmed, and\n\t// callers must refuse rather than fall back to the owner's permissions.\n\tGetAPIKeyEffectivePermissionsAPI(ctx context.Context, keyID, userID string) ([]auth.APIPermission, error)\n\t// Account access - returns the union of allowed_accounts from all user groups (empty = all access)\n\tGetAllowedAccountsAPI(ctx context.Context, userID string) ([]string, error)\n\t// API Key management\n\t// CreateAPIKeyAPI takes the auth wire type directly: re-encoding a local\n\t// copy erased an explicit max_amount of 0 (issue #980).\n\tCreateAPIKeyAPI(ctx context.Context, userID string, req auth.APICreateAPIKeyRequest) (any, error)\n\tListUserAPIKeysAPI(ctx context.Context, userID string) (any, error)\n\t// GetAPIKeysUsageStatsAPI returns the section-level usage summary\n\t// (active count, fixed-window/lifetime request totals, top-3 most\n\t// active keys) for the calling user's own API keys.\n\tGetAPIKeysUsageStatsAPI(ctx context.Context, userID string) (any, error)\n\tDeleteAPIKeyAPI(ctx context.Context, userID, keyID string) error\n\tRevokeAPIKeyAPI(ctx context.Context, userID, keyID string) error\n\tValidateUserAPIKeyAPI(ctx context.Context, apiKey string) (any, any, error)\n\t// RecordAPIKeyUsageAsync books exactly one request against the given\n\t// API key ID (the last_used_at timestamp plus the lifetime and\n\t// fixed-window request counters). Fire-and-forget: the store write\n\t// happens off the request path, so it returns nothing and never delays\n\t// or fails the caller's request.\n\t//\n\t// Must be called once per inbound request and only from\n\t// Handler.validateSecurityContext. Calling it from a credential\n\t// validation path instead would count validations, which a single\n\t// request performs several times over.\n\tRecordAPIKeyUsageAsync(keyID string)\n\t// HasAPIKeyPermissionAPI validates a user API key and checks the\n\t// requested action/resource against the key's effective permissions\n\t// (the intersection of the key's scoped permissions with the owning\n\t// user's group-derived permissions). Returns the owning user's ID, the\n\t// key's database ID, and whether the permission is held; a non-nil error\n\t// means the key did not validate or the lookup failed, and callers must\n\t// deny (fail closed). Wired into requirePermission so per-key scoping is\n\t// enforced at request time (issue #1142).\n\tHasAPIKeyPermissionAPI(ctx context.Context, apiKey, action, resource string) (userID, keyID string, allowed bool, err error)\n\t// HasAPIKeyPermissionForConstraintsAPI checks request-derived permission\n\t// constraint sets against a user API key's effective permissions (the\n\t// intersection of the key's own constraints and the owning user's\n\t// group-derived permissions). Must be called after HasAPIKeyPermissionAPI\n\t// confirms action/resource access. Enforces per-key caps (MaxPurchaseAmount,\n\t// Providers, Services, Regions, AccountIDs) that the key's owner cannot\n\t// override via their broader group permissions (adversarial-review F2).\n\tHasAPIKeyPermissionForConstraintsAPI(ctx context.Context, keyID, userID, action, resource string, constraintSets []auth.PermissionConstraints) (bool, error)\n}\n```\nAuthServiceInterface defines auth service methods used by handler Note: This interface uses API-specific types that are converted from auth package types.\n\n```go\ntype AzureCompatibleOfferingsRequestBody struct {\n\tSubscriptionID string                    `json:\"subscription_id\"`\n\tSources        []AzureExchangeSourceBody `json:\"sources\"`\n\tTargets        []AzureExchangeTargetBody `json:\"targets\"`\n}\n```\nAzureCompatibleOfferingsRequestBody is the request body for the compatible-offerings endpoint.\n\n```go\ntype AzureCompatibleOfferingsResponse struct {\n\tPreview   *azureExchangePreview     `json:\"preview\"`\n\tOfferings []azureCompatibleOffering `json:\"offerings\"`\n}\n```\nAzureCompatibleOfferingsResponse is the response for the compatible-offerings endpoint: the priced candidate offerings plus the preview (including the SessionID a subsequent execute call would need, though execute never trusts a client-supplied session -- see executeAzureExchange).\n\n```go\ntype AzureExchangeSourceBody struct {\n\tReservationID string `json:\"reservation_id\"`\n\tQuantity      int32  `json:\"quantity\"`\n}\n```\nAzureExchangeSourceBody is one source reservation entry in an Azure compatible-offerings or execute request body.\n\n```go\ntype AzureExchangeTargetBody struct {\n\tSKU      string `json:\"sku\"`\n\tLocation string `json:\"location\"`\n\tTerm     string `json:\"term\"`\n\t// BillingScopeID is optional and is NOT the scope that gets charged:\n\t// the handler always derives that from the request's authorized\n\t// subscription_id (azureBillingScopeID), matching every other Azure\n\t// reservation purchase path in this repo. When supplied it must match\n\t// the derived scope, so a caller cannot direct the charge at a\n\t// different subscription than the one their permission constraints\n\t// were evaluated against.\n\tBillingScopeID string `json:\"billing_scope_id,omitempty\"`\n\tQuantity       int32  `json:\"quantity\"`\n}\n```\nAzureExchangeTargetBody is one target entry. Term is the ISO 8601 reservation term string (\"P1Y\", \"P3Y\", ...); azureReservationTermFromString validates it against the SDK's typed enum rather than accepting anything the caller sends.\n\n```go\ntype AzureExecuteExchangeRequestBody struct {\n\tSubscriptionID string                    `json:\"subscription_id\"`\n\tMaxPaymentDue  string                    `json:\"max_payment_due\"`\n\tCurrency       string                    `json:\"currency\"`\n\tSources        []AzureExchangeSourceBody `json:\"sources\"`\n\tTargets        []AzureExchangeTargetBody `json:\"targets\"`\n}\n```\nAzureExecuteExchangeRequestBody is the request body for the execute endpoint. MaxPaymentDue + Currency are mandatory safety guardrails: the handler refuses to execute an exchange whose fresh quote exceeds the cap or is denominated in a different currency.\n\n```go\ntype AzureExecuteExchangeResponse struct {\n\tNetPayable         *float64 `json:\"net_payable\"`\n\tRefundsTotal       *float64 `json:\"refunds_total\"`\n\tPurchasesTotal     *float64 `json:\"purchases_total\"`\n\tSessionID          string   `json:\"session_id\"`\n\tStatus             string   `json:\"status\"`\n\tNetPayableCurrency string   `json:\"net_payable_currency,omitempty\"`\n}\n```\nAzureExecuteExchangeResponse is the response from a successfully executed Azure exchange.\n\n```go\ntype BreakdownResponse struct {\n\tData      map[string]BreakdownValue `json:\"data\"`\n\tDimension string                    `json:\"dimension\"`\n\tStart     string                    `json:\"start\"`\n\tEnd       string                    `json:\"end\"`\n}\n```\nBreakdownResponse represents the response for the breakdown endpoint.\n\n```go\ntype BreakdownValue struct {\n\tTotalUpfront  *float64 `json:\"total_upfront\"`\n\tTotalSavings  float64  `json:\"total_savings\"`\n\tPurchaseCount int      `json:\"purchase_count\"`\n\tPercentage    float64  `json:\"percentage\"`\n}\n```\nBreakdownValue represents savings breakdown by dimension.\n\n```go\ntype ChangePasswordRequest struct {\n\tCurrentPassword string `json:\"current_password\"`\n\tNewPassword     string `json:\"new_password\"`\n}\n```\nChangePasswordRequest represents a request to change password.\n\n```go\ntype CloudAccountRequest struct {\n\tEnabled                 *bool  `json:\"enabled\"`\n\tAWSIsOrgRoot            *bool  `json:\"aws_is_org_root\"`\n\tAWSWebIdentityTokenFile string `json:\"aws_web_identity_token_file\"`\n\tAzureClientID           string `json:\"azure_client_id\"`\n\tProvider                string `json:\"provider\"`\n\tName                    string `json:\"name\"`\n\tDescription             string `json:\"description\"`\n\tAWSAuthMode             string `json:\"aws_auth_mode\"`\n\tAWSRoleARN              string `json:\"aws_role_arn\"`\n\tAWSExternalID           string `json:\"aws_external_id\"`\n\tContactEmail            string `json:\"contact_email\"`\n\tGCPWIFAudience          string `json:\"gcp_wif_audience\"`\n\tExternalID              string `json:\"external_id\"`\n\tAzureSubscriptionID     string `json:\"azure_subscription_id\"`\n\tAzureTenantID           string `json:\"azure_tenant_id\"`\n\tAWSBastionID            string `json:\"aws_bastion_id\"`\n\tAzureAuthMode           string `json:\"azure_auth_mode\"`\n\tGCPProjectID            string `json:\"gcp_project_id\"`\n\tGCPClientEmail          string `json:\"gcp_client_email\"`\n\tGCPAuthMode             string `json:\"gcp_auth_mode\"`\n}\n```\nCloudAccountRequest is the request body for create/update account endpoints. Enabled and AWSIsOrgRoot are pointers so an omitted (or null) key can be told apart from an explicit false: create treats absent as false, update keeps the stored value (issue #151, A02-013).\n\n```go\ntype CommitmentOptsInterface interface {\n\tGet(ctx context.Context) (commitmentopts.Options, error)\n\t// CachedOptions reads one provider's stored combos without probing.\n\tCachedOptions(ctx context.Context, provider string) (map[string][]commitmentopts.Combo, bool, error)\n\t// FreshAzureOptions is CachedOptions(\"azure\") limited to a row inside its\n\t// TTL; ok is false for an unprobed or stale row.\n\tFreshAzureOptions(ctx context.Context) (map[string][]commitmentopts.Combo, bool, error)\n\tValidate(ctx context.Context, provider, service string, term int, payment string) (bool, error)\n}\n```\nCommitmentOptsInterface lets us swap the real \\*commitmentopts.Service for a stub in handler tests without pulling in the probe+store machinery.\n\n```go\ntype ConfigResponse struct {\n\tGlobal         *config.GlobalConfig   `json:\"global\"`\n\tSourceIdentity *sourceIdentity        `json:\"source_identity,omitempty\"`\n\tSourceCloud    string                 `json:\"source_cloud,omitempty\"`\n\tServices       []config.ServiceConfig `json:\"services\"`\n}\n```\nConfigResponse holds the configuration response.\n\n```go\ntype ConvertibleRIsResponse struct {\n\tInstances []convertibleRIWithAccount `json:\"instances\"`\n}\n```\nConvertibleRIsResponse holds the list of convertible RIs.\n\n```go\ntype CoverageBreakdownResponse struct {\n\tProviders []ProviderCoverageSection `json:\"providers\"`\n}\n```\nCoverageBreakdownResponse is the envelope returned by GET /api/inventory/coverage.\n\n```go\ntype CoverageServiceRow struct {\n\tCoveragePct     *float64 `json:\"coverage_pct\"`\n\tCoveredMonthly  *float64 `json:\"covered_monthly\"`\n\tService         string   `json:\"service\"`\n\tOnDemandMonthly float64  `json:\"on_demand_monthly\"`\n}\n```\nCoverageServiceRow is one service row within a provider's coverage section. CoveredMonthly is the sum of active-commitment MonthlyCost values for the (provider, service) pair. OnDemandMonthly is the sum of recommendation Savings values — i.e. the portion of on-demand spend that is NOT yet committed. CoveragePct is nil when both sums are zero (no usage detected), not 0, to preserve the \"absent\" semantic per feedback\\_nullable\\_not\\_zero.\n\n```go\ntype CreateAPIKeyResponse struct {\n\tInfo   *APIKeyInfo `json:\"info\"`\n\tAPIKey string      `json:\"api_key\"` //nolint:gosec // G117: intentional one-time serialization -- this response returns the newly created key to its owner; the key is never re-stored or re-serialized\n\tKeyID  string      `json:\"key_id\"`\n}\n```\nCreateAPIKeyResponse returns the newly created API key (only shown once).\n\n```go\ntype CreatePlannedPurchasesRequest struct {\n\tStartDate string `json:\"start_date\"`\n\tCount     int    `json:\"count\"`\n}\n```\nCreatePlannedPurchasesRequest represents a request to create planned purchases.\n\n```go\ntype CreatePlannedPurchasesResponse struct {\n\tCreated int `json:\"created\"`\n}\n```\nCreatePlannedPurchasesResponse represents the response after creating planned purchases.\n\n```go\ntype CredentialsRequest struct {\n\tPayload        map[string]interface{} `json:\"payload\"`\n\tCredentialType string                 `json:\"credential_type\"`\n}\n```\nCredentialsRequest is the request body for the save-credentials endpoint.\n\n```go\ntype CurrentUserResponse struct {\n\tID         string   `json:\"id\"`\n\tEmail      string   `json:\"email\"`\n\tCSRFToken  string   `json:\"csrf_token,omitempty\"`\n\tGroups     []string `json:\"groups,omitempty\"`\n\tMFAEnabled bool     `json:\"mfa_enabled\"`\n}\n```\nCurrentUserResponse holds the current user response.\n\n```go\ntype DBRateLimiter struct {\n\t// contains filtered or unexported fields\n}\n```\nDBRateLimiter provides distributed rate limiting using the database This implementation uses a sliding window algorithm with the database as the backend, making it suitable for Lambda functions and distributed systems.\n\n```go\nfunc NewDBRateLimiter(pool *pgxpool.Pool) *DBRateLimiter\n```\nNewDBRateLimiter creates a new database-backed rate limiter. Call StartCleanupWorker on the returned limiter to ensure periodic cleanup of expired rows independent of traffic (addresses 02-M2).\n\n```go\nfunc (rl *DBRateLimiter) Allow(ctx context.Context, key, endpoint string) (bool, error)\n```\nAllow checks if a request should be allowed based on rate limits. The key should be formatted as \"IP#{ip}\" or \"EMAIL#{email}\". The endpoint identifies which rate limit configuration to use.\n\nImplementation: a single atomic INSERT ... ON CONFLICT DO UPDATE statement performs the read-modify-write in one round trip, so two concurrent first-requests for the same id can never collide on the PK (the older check-then-insert flow hit SQLSTATE 23505 in production — see commit 9fa4170a1's sibling note in known\\_issues/05\\_config\\_store\\_postgres.md).\n\nBehavior: each call increments \\`count\\` (or resets to 1 if the window has expired). The returned \\`count\\` is then compared to \\`config.MaxAttempts\\` to decide allow/deny. \\`count\\` may temporarily drift past MaxAttempts under sustained over-limit traffic — the rate limiter still denies correctly, and \\`cleanup()\\` evicts expired rows on its 24-hour cycle. This is a small accounting trade for atomicity and is acceptable for rate-limit semantics.\n\n```go\nfunc (rl *DBRateLimiter) AllowWithEmail(ctx context.Context, email, endpoint string) (bool, error)\n```\nAllowWithEmail is a convenience method that formats the key as an email-based key.\n\n```go\nfunc (rl *DBRateLimiter) AllowWithIP(ctx context.Context, ip, endpoint string) (bool, error)\n```\nAllowWithIP is a convenience method that formats the key as an IP-based key.\n\n```go\nfunc (rl *DBRateLimiter) AllowWithUser(ctx context.Context, userID, endpoint string) (bool, error)\n```\nAllowWithUser is a convenience method that formats the key as a user-based key.\n\n```go\nfunc (rl *DBRateLimiter) SetLimit(endpoint string, config RateLimitConfig)\n```\nSetLimit allows customizing rate limits for specific endpoints.\n\n```go\nfunc (rl *DBRateLimiter) StartCleanupWorker(ctx context.Context)\n```\nStartCleanupWorker launches a background goroutine that calls cleanup() on a fixed schedule, independent of the count==1 opportunistic trigger.\n\nThis ensures that perpetually-denied keys (whose count never resets to 1) are also evicted, preventing unbounded row growth on the rate\\_limits table under sustained abuse (02-M2). The goroutine stops when ctx is canceled.\n\nCall this once at server startup after creating the DBRateLimiter. The goroutine is lightweight (one blocked timer channel) and safe to call from tests with a short-lived context.\n\n```go\ntype DashboardSummaryResponse struct {\n\tByService map[string]ServiceSavings `json:\"by_service\"`\n\t// CurrentCoverage is null when there is neither committed nor potential\n\t// savings to measure (0/0), instead of a fabricated 100% (issue #72).\n\tCurrentCoverage         *float64 `json:\"current_coverage\"`\n\tPotentialMonthlySavings float64  `json:\"potential_monthly_savings\"`\n\tTotalRecommendations    int      `json:\"total_recommendations\"`\n\tActiveCommitments       int      `json:\"active_commitments\"`\n\t// CommittedMonthly is the estimated monthly savings of the active\n\t// commitments (the sum of their EstimatedSavings), not their cost (#1709).\n\tCommittedMonthly float64 `json:\"committed_monthly\"`\n\t// ExcludedLegacyEstimateCount is how many of ActiveCommitments are Azure\n\t// rows with legacy-estimate amounts (issue #669). Their dollars are not in\n\t// CommittedMonthly, YTDSavings or the per-service current savings.\n\tExcludedLegacyEstimateCount int     `json:\"excluded_legacy_estimate_count\"`\n\tTargetCoverage              float64 `json:\"target_coverage\"`\n\tYTDSavings                  float64 `json:\"ytd_savings\"`\n}\n```\nDashboardSummaryResponse holds the dashboard summary data.\n\n```go\ntype DeletePlannedPurchaseResponse struct {\n\tPlanDisabled *bool  `json:\"plan_disabled,omitempty\"`\n\tStatus       string `json:\"status\"`\n}\n```\nDeletePlannedPurchaseResponse is the body of DELETE /api/purchases/planned/{id}. PlanDisabled is omitted when the execution has no plan and true when the plan was disabled. A plan the caller may not disable fails the request (403 before the cancel, 409 if the plan changed after it) instead of reporting false (issues #520, #623).\n\n```go\ntype DeploymentInfoResponse struct {\n\t// APIKeySecretURL is the AWS Console deep-link to the Secrets Manager\n\t// secret holding the CUDly API key.\n\tAPIKeySecretURL string `json:\"api_key_secret_url,omitempty\"`\n\t// DeploymentAWSAccountID is the AWS account ID of the Lambda host,\n\t// resolved via STS GetCallerIdentity. Empty on non-AWS deployments\n\t// or when STS is unreachable. Used by the frontend to distinguish\n\t// legitimate ambient-credential executions from orphan rows (#608).\n\tDeploymentAWSAccountID string `json:\"deployment_aws_account_id,omitempty\"`\n}\n```\nDeploymentInfoResponse holds deployment-scoped identifiers that must not be exposed to unauthenticated callers. Served by GET /api/info/deployment (AuthUser).\n\n```go\ntype DiscoverOrgRequest struct {\n\tAccountID string `json:\"account_id\"`\n}\n```\nDiscoverOrgRequest is the request body for POST /api/accounts/discover-org. AccountID is the UUID of the org-root cloud account whose stored credentials will be used to call AWS Organizations.\n\n```go\ntype DiscoverOrgResult struct {\n\tDiscovered int `json:\"discovered\"`\n\tCreated    int `json:\"created\"`\n\tSkipped    int `json:\"skipped\"`\n}\n```\nDiscoverOrgResult is the response shape for POST /api/accounts/discover-org. Discovered is the total number of member accounts the AWS Organizations API returned; Created is the number of new cloud\\_accounts rows persisted; Skipped is the number that already existed (matched by provider+external\\_id).\n\n```go\ntype EmptyServiceConfigResponse struct{}\n```\nEmptyServiceConfigResponse represents an empty service config.\n\n```go\ntype ExchangeExecuteRequestBody struct {\n\tTargetOfferingID string               `json:\"target_offering_id,omitempty\"`\n\tMaxPaymentDueUSD string               `json:\"max_payment_due_usd\"`\n\tRegion           string               `json:\"region,omitempty\"`\n\tRIIDs            []string             `json:\"ri_ids\"`\n\tTargets          []ExchangeTargetBody `json:\"targets,omitempty\"`\n\tTargetCount      int32                `json:\"target_count,omitempty\"`\n}\n```\nExchangeExecuteRequestBody is the request body for the execute endpoint. Same \\`targets\\` / legacy-alias semantics as ExchangeQuoteRequestBody. \\`max\\_payment\\_due\\_usd\\` is a TOTAL cap across all targets in the exchange — AWS returns a single aggregated PaymentDue so spend-cap checking naturally becomes a total when \\`targets\\[]\\` has multiple entries.\n\n```go\ntype ExchangeExecuteResponse struct {\n\tQuote      *exchange.ExchangeQuoteSummary `json:\"quote\"`\n\tExchangeID string                         `json:\"exchange_id\"`\n}\n```\nExchangeExecuteResponse is the response from a successful exchange execution.\n\n```go\ntype ExchangeQuoteRequestBody struct {\n\tTargetOfferingID string               `json:\"target_offering_id,omitempty\"`\n\tRegion           string               `json:\"region,omitempty\"`\n\tRIIDs            []string             `json:\"ri_ids\"`\n\tTargets          []ExchangeTargetBody `json:\"targets,omitempty\"`\n\tTargetCount      int32                `json:\"target_count,omitempty\"`\n}\n```\nExchangeQuoteRequestBody is the request body for the quote endpoint. Callers may supply either the new \\`targets\\` array (preferred) or the legacy \\`target\\_offering\\_id\\` + \\`target\\_count\\` singleton fields. When both are present, \\`targets\\` wins. Exactly one of them must be provided (or the handler returns 400).\n\n```go\ntype ExchangeQuoteResponse struct {\n\t*exchange.ExchangeQuoteSummary\n\tRegion string `json:\"Region\"`\n}\n```\nExchangeQuoteResponse is the library's quote summary plus the region the quote was priced in, which callers must send back on execute. The embedded pointer promotes the summary's fields to the JSON top level.\n\n```go\ntype ExchangeTargetBody struct {\n\tOfferingID string `json:\"offering_id\"`\n\tCount      int32  `json:\"count\"`\n}\n```\nExchangeTargetBody is one entry in an ExchangeQuote/Execute request's \\`targets\\` array. Mirrors pkg/exchange.TargetConfig but with JSON tags shaped for the HTTP surface.\n\n```go\ntype ExchangeableAzureRIsResponse struct {\n\tReservations []azureExchangeableReservation `json:\"reservations\"`\n}\n```\nExchangeableAzureRIsResponse holds the list of Azure VM reservations that are eligible for the cross-SKU/cross-region exchange flow.\n\n```go\ntype ExcludedRI struct {\n\tRIID   string `json:\"ri_id\"`\n\tReason string `json:\"reason\"`\n}\n```\nExcludedRI names a convertible RI omitted from reshape analysis and why.\n\n```go\ntype ExecutePurchaseRequest struct {\n\t// ExecuteMode controls whether this request bypasses the approval\n\t// email and executes the purchase immediately. The only accepted\n\t// non-empty value is \"direct\"; any other value is treated as the\n\t// default approval-required flow. The handler re-checks the\n\t// execute-any/execute-own RBAC gate before honoring \"direct\",\n\t// even if the session already passed the execute:purchases gate in\n\t// validateExecutePurchaseRequest, so a client that sets this field\n\t// without the privilege receives a 403 rather than silent fallback.\n\tExecuteMode string `json:\"execute_mode,omitempty\"`\n\t// Recommendations are matched against the stored recommendation set on\n\t// (provider, cloud_account_id, service, region, resource_type, engine,\n\t// term, payment). Only count, recommended_count and selected are taken\n\t// from the request; id, details and every cost field are replaced from\n\t// the stored row scaled by count (priceRecommendationsFromStore, #1905).\n\tRecommendations []config.RecommendationRecord `json:\"recommendations\"`\n\t// CapacityPercent is what fraction (1..100) of the originally-\n\t// recommended counts the user chose in the bulk Purchase flow.\n\t// Count-based recommendations already carry scaled counts, so the\n\t// backend only audits it for them. A Savings Plans recommendation keeps\n\t// Count 1 and is sized here: the hourly commitment is scaled by this\n\t// percentage (priceFromStored, #1959).\n\t// 0 / absent defaults to 100 (\"full capacity\").\n\tCapacityPercent int `json:\"capacity_percent,omitempty\"`\n}\n```\nExecutePurchaseRequest represents the request to execute purchases.\n\n```go\ntype FederationIaCResponse struct {\n\tFilename        string `json:\"filename\"`\n\tContent         string `json:\"content\"`\n\tContentType     string `json:\"content_type\"`\n\tContentEncoding string `json:\"content_encoding,omitempty\"` // \"base64\" for binary (zip)\n}\n```\nFederationIaCResponse is returned by the /api/federation/iac endpoint.\n\n```go\ntype Group struct {\n\tID              string       `json:\"id\"`\n\tName            string       `json:\"name\"`\n\tDescription     string       `json:\"description,omitempty\"`\n\tCreatedAt       string       `json:\"created_at,omitempty\"`\n\tUpdatedAt       string       `json:\"updated_at,omitempty\"`\n\tPermissions     []Permission `json:\"permissions\"`\n\tAllowedAccounts []string     `json:\"allowed_accounts,omitempty\"`\n}\n```\nGroup represents a user group with permissions.\n\n```go\ntype Handler struct {\n\t// contains filtered or unexported fields\n}\n```\nHandler processes HTTP requests.\n\n```go\nfunc NewHandler(cfg HandlerConfig) *Handler\n```\nNewHandler creates a new API handler.\n\n```go\nfunc (h *Handler) FetchRecommendationComparison(ctx context.Context, rec *archera.RecommendationIdentity) (*insurance.Comparison, []insurance.LineItem, error)\n```\nFetchRecommendationComparison reads every line item, selects the recommendation's own one and asks for a comparison scoped to it. No line item, or an ambiguous one, returns an empty comparison without a comparison call. Any failure returns no partial result.\n\n```go\nfunc (h *Handler) GetHealth(ctx context.Context) (*HealthResponse, error)\n```\nGetHealth performs comprehensive health checks.\n\n```go\nfunc (h *Handler) HandleOIDC(ctx context.Context, req *events.LambdaFunctionURLRequest) (*events.LambdaFunctionURLResponse, bool)\n```\nHandleOIDC serves the two OIDC issuer endpoints directly, without going through the API router. Both are always public (no auth, no CSRF). Returns nil if path is not an OIDC discovery path so the caller can fall through to the main router.\n\nThe Azure federated credential path also reads the resolved issuer URL via oidc.IssuerURL(), so calling this endpoint once populates the shared cache — which is how the purchase manager (no HTTP context) learns what iss claim to put in its client\\_assertion JWTs.\n\n```go\nfunc (h *Handler) HandleRequest(ctx context.Context, req *events.LambdaFunctionURLRequest) (*events.LambdaFunctionURLResponse, error)\n```\nHandleRequest processes a Lambda Function URL request.\n\n```go\nfunc (h *Handler) IsLambda() bool\n```\nIsLambda reports the Lambda mode this handler was constructed with (HandlerConfig.IsLambda). It never re-reads the environment.\n\n```go\nfunc (h *Handler) NextCollectionAt(now time.Time) *time.Time\n```\nNextCollectionAt returns the next scheduled collection strictly after now, or nil when it is unknown: no schedule, a rate() schedule (whose phase the runtime cannot see) or no fire time within the search horizon. Exported so the server package can check the schedule is wired through.\n\n```go\nfunc (h *Handler) PollMarketplaceListings(ctx context.Context) (*MarketplacePollResult, error)\n```\nPollMarketplaceListings reads every listing due for a poll from AWS and records what changed. A failure on one listing is logged and counted, and the run goes on with the next; only failing to list the rows, or the context ending, fails the run.\n\n```go\ntype HandlerConfig struct {\n\tEmailNotifier       email.SenderInterface\n\tAnalyticsSnapshots  AnalyticsSnapshotStoreInterface\n\tPurchaseManager     PurchaseManagerInterface\n\tRateLimiter         RateLimiterInterface\n\tAuthService         AuthServiceInterface\n\tCommitmentOpts      CommitmentOptsInterface\n\tOIDCSigner          oidc.Signer\n\tConfigStore         config.StoreInterface\n\tScheduler           SchedulerInterface\n\tCredentialStore     credentials.CredentialStore\n\tAnalyticsCollector  AnalyticsCollectorInterface\n\tAnalyticsClient     AnalyticsClientInterface\n\tInsurance           InsuranceProvider\n\tDashboardURL        string\n\tCORSAllowedOrigin   string\n\tDashboardBucket     string\n\tOIDCIssuerURL       string\n\tAPIKeySecretARN     string\n\tEncryptionKeySource string\n\t// RecommendationSchedule is the deployment's recommendation-collection\n\t// schedule (RECOMMENDATION_SCHEDULE, set by Terraform). Empty means\n\t// scheduled collection is off or the deployment predates the variable.\n\t// It feeds next_collection_at on GET /api/recommendations/freshness.\n\tRecommendationSchedule string\n\tEnableDashboard        bool\n\t// IsLambda is the caller's (Application's) single answer to \"am I on\n\t// Lambda\". It gates the background goroutines (RI utilization SWR\n\t// refresh, stale-execution sweep) that would freeze mid-flight on Lambda.\n\t// The handler never re-reads the environment itself (issue #110).\n\tIsLambda bool\n\t// FireSweepOff is true when Terraform says no fire_scheduled_purchases\n\t// sweep runs (FIRE_SWEEP_SCHEDULED=false). A delayed approval would then\n\t// sit in \"scheduled\" forever, so PUT /api/config refuses a delay (#1588).\n\t// False when the variable is unset, so older deployments keep saving.\n\tFireSweepOff bool\n}\n```\nHandlerConfig holds configuration for the API handler.\n\n```go\ntype HealthCheck struct {\n\tStatus  string `json:\"status\"`\n\tMessage string `json:\"message,omitempty\"`\n}\n```\nHealthCheck represents a single health check result.\n\n```go\ntype HealthResponse struct {\n\tTimestamp time.Time              `json:\"timestamp\"`\n\tChecks    map[string]HealthCheck `json:\"checks\"`\n\tStatus    string                 `json:\"status\"`\n}\n```\nHealthResponse represents the health check response.\n\n```go\ntype HistoryDataPoint struct {\n\tTimestamp         time.Time          `json:\"timestamp\"`\n\tByService         map[string]float64 `json:\"by_service,omitempty\"`\n\tByProvider        map[string]float64 `json:\"by_provider,omitempty\"`\n\tTotalUpfront      *float64           `json:\"total_upfront\"`\n\tTotalSavings      float64            `json:\"total_savings\"`\n\tPurchaseCount     int                `json:\"purchase_count\"`\n\tCumulativeSavings float64            `json:\"cumulative_savings\"`\n}\n```\nHistoryDataPoint represents aggregated historical data.\n\n```go\ntype HistoryResponse struct {\n\t// NextCursor is the opaque position after the last paged row of this\n\t// response, set only when HasMore is true.\n\tNextCursor string                         `json:\"next_cursor,omitempty\"`\n\tPurchases  []config.PurchaseHistoryRecord `json:\"purchases\"`\n\t// Summary covers every row matching the request's filters and the caller's\n\t// account scope, including rows beyond the row caps (issue #675), unless\n\t// SummaryComplete is false.\n\tSummary HistorySummary `json:\"summary\"`\n\t// Limit is the page size: the most completed purchase_history rows and\n\t// terminal executions (failed, expired, canceled, ...) together that one\n\t// response lists (issue #674).\n\tLimit int `json:\"limit\"`\n\t// ExecutionsLimit is the row cap on terminal executions. They share the\n\t// page with completed purchases, so it equals Limit.\n\t// Actionable executions (pending, approved, ...) use ActionableExecutionsLimit.\n\tExecutionsLimit int `json:\"executions_limit\"`\n\t// ActionableExecutionsLimit is the row cap on actionable executions\n\t// (pending, notified, scheduled, approved, running, paused), fixed at\n\t// config.MaxListLimit regardless of the request's limit parameter.\n\t// Actionable executions are not paged: the first page lists them all, up\n\t// to this cap, and pages fetched with a cursor leave them out.\n\tActionableExecutionsLimit int `json:\"actionable_executions_limit\"`\n\t// SummaryComplete is true when Summary was computed over every matching\n\t// row. It is false only when that aggregate failed and Summary fell back\n\t// to the rows in Purchases, which under-reports when Truncated is true.\n\tSummaryComplete bool `json:\"summary_complete\"`\n\t// Truncated is true when a fetch reached its row cap, so older rows (and\n\t// possibly pending approvals) may be missing from Purchases. Summary still\n\t// counts them while SummaryComplete is true.\n\t// It also fires when the actionable execution class hits its MaxListLimit cap,\n\t// and when an execution class listing failed, so its rows are missing.\n\t// It can be a false positive when exactly a cap's worth of rows exist.\n\tTruncated bool `json:\"truncated\"`\n\t// HasMore is true when more completed purchases or terminal executions the\n\t// caller may see follow this page; pass NextCursor as the cursor parameter\n\t// to fetch them (issue #674). Truncated is also true then.\n\tHasMore bool `json:\"has_more\"`\n}\n```\nHistoryResponse represents the response from the history API.\n\n```go\ntype HistorySummary struct {\n\tTotalUpfront   *float64 `json:\"total_upfront\"`\n\tTotalPurchases int      `json:\"total_purchases\"`\n\tTotalCompleted int      `json:\"total_completed\"`\n\tTotalPending   int      `json:\"total_pending\"`\n\t// TotalInProgress counts executions that have been approved but whose\n\t// synchronous purchase has not finalized (status approved/running/paused).\n\t// Tracked separately from pending and excluded from the dollar totals so an\n\t// interrupted approval (issue #621) stays visible without inflating\n\t// committed spend/savings.\n\tTotalInProgress int `json:\"total_in_progress\"`\n\tTotalFailed     int `json:\"total_failed\"`\n\tTotalExpired    int `json:\"total_expired\"`\n\t// TotalRevoked counts commitments that have been revoked/refunded via\n\t// MarkPurchaseRevoked. They are excluded from TotalCompleted and all dollar\n\t// totals because the provider has canceled the commitment.\n\tTotalRevoked        int     `json:\"total_revoked\"`\n\tTotalMonthlySavings float64 `json:\"total_monthly_savings\"`\n\tTotalAnnualSavings  float64 `json:\"total_annual_savings\"`\n}\n```\nHistorySummary provides aggregate statistics for purchase history. TotalPurchases is the total count of rows (completed + all non-completed states); the per-state counters break it down so the UI can render meaningful totals. Dollar totals count completed, non-revoked rows only: pending, in-progress, failed, expired, canceled, and revoked rows are all excluded because no money is being actively committed for those states.\n\n```go\ntype InMemoryRateLimiter struct {\n\t// contains filtered or unexported fields\n}\n```\nInMemoryRateLimiter holds process-local counters for explicitly single-process use or temporary initialization. Replicated deployments must use DBRateLimiter.\n\n```go\nfunc NewInMemoryRateLimiter() *InMemoryRateLimiter\n```\nNewInMemoryRateLimiter creates a new in-memory rate limiter for single-instance deployments.\n\n```go\nfunc (rl *InMemoryRateLimiter) Allow(ctx context.Context, key, endpoint string) (bool, error)\n```\nAllow checks if a request should be allowed based on rate limits. The key should be formatted as \"IP#{ip}\" or \"EMAIL#{email}\". The endpoint identifies which rate limit configuration to use.\n\n```go\nfunc (rl *InMemoryRateLimiter) AllowWithEmail(ctx context.Context, email, endpoint string) (bool, error)\n```\nAllowWithEmail is a convenience method that formats the key as an email-based key.\n\n```go\nfunc (rl *InMemoryRateLimiter) AllowWithIP(ctx context.Context, ip, endpoint string) (bool, error)\n```\nAllowWithIP is a convenience method that formats the key as an IP-based key.\n\n```go\nfunc (rl *InMemoryRateLimiter) AllowWithUser(ctx context.Context, userID, endpoint string) (bool, error)\n```\nAllowWithUser is a convenience method that formats the key as a user-based key.\n\n```go\nfunc (rl *InMemoryRateLimiter) SetLimit(endpoint string, config RateLimitConfig)\n```\nSetLimit allows customizing rate limits for specific endpoints.\n\n```go\ntype InsuranceProvider interface {\n\tStatus() archera.Status\n\tPlanID() string\n\tClient(ctx context.Context) (insurance.QuoteClient, error)\n}\n```\nInsuranceProvider is the Archera comparison surface. nil means not wired.\n\n```go\ntype InventoryCommitment struct {\n\tStartDate time.Time `json:\"start_date\"`\n\tEndDate   time.Time `json:\"end_date\"`\n\t// MonthlyCost is nil when the source purchase_history row has a NULL\n\t// monthly_cost (provider did not return a monthly breakdown). The\n\t// frontend renders \"--\" for nil and \"$X.XX\" when non-nil.\n\tMonthlyCost   *float64 `json:\"monthly_cost\"`\n\tUpfrontCost   *float64 `json:\"upfront_cost\"`\n\tRegion        string   `json:\"region\"`\n\tAccountName   string   `json:\"account_name,omitempty\"`\n\tService       string   `json:\"service\"`\n\tResourceType  string   `json:\"resource_type,omitempty\"`\n\tAccountID     string   `json:\"account_id\"`\n\tStatus        string   `json:\"status\"`\n\tID            string   `json:\"id\"`\n\tPaymentOption string   `json:\"payment_option,omitempty\"`\n\tProvider      string   `json:\"provider\"`\n\t// AmountBasis is \"legacy_window\" when the dollar amounts are a legacy\n\t// estimate (issue #669); omitted for normal rows.\n\tAmountBasis      config.PurchaseAmountBasis `json:\"amount_basis,omitempty\"`\n\tTermYears        int                        `json:\"term_years\"`\n\tEstimatedSavings float64                    `json:\"estimated_savings\"`\n\tCount            int                        `json:\"count\"`\n}\n```\nInventoryCommitment is one row in the per-commitment Inventory \u0026 Coverage view (issue #340 deferred sub-task — \"Active commitments\"). Aggregated from PurchaseHistoryRecord rows that are still within their term; the inventory endpoint filters out expired commitments before responding.\n\nID is \\`{account\\_id}:{purchase\\_id}\\` so the row is uniquely identifiable in the JSON payload without a DB schema change — purchase\\_id alone is unique within an account but not globally across the table.\n\nStatus is always \\`\"active\"\\` today (the handler drops expired rows). The field stays in the response shape so a future \"expiring soon\" sub-state has a slot without a breaking API change.\n\n```go\ntype InventoryCommitmentsResponse struct {\n\tCommitments []InventoryCommitment `json:\"commitments\"`\n}\n```\nInventoryCommitmentsResponse is the envelope returned by GET /api/inventory/commitments. Commitments is always a slice — never nil — so the frontend can rely on \\`resp.commitments.length\\` without a null check.\n\n```go\ntype LambdaInvokerInterface interface {\n\tInvoke(ctx context.Context, params *lambda.InvokeInput, optFns ...func(*lambda.Options)) (*lambda.InvokeOutput, error)\n}\n```\nLambdaInvokerInterface is the narrow subset of lambda.Client used by the async refresh handler. Extracted so tests can inject a stub without standing up a real Lambda client.\n\n```go\ntype LoginRequest struct {\n\tEmail    string `json:\"email\"`\n\tPassword string `json:\"password\"` //nolint:gosec // G117: intentional credential field in request/response struct -- value is supplied by the authenticated caller or returned once at creation; not re-stored downstream\n\tMFACode  string `json:\"mfa_code,omitempty\"`\n\t// MFAToken is the continuation token from an mfa_required answer\n\t// (issue #134), sent with Email and MFACode in place of Password.\n\tMFAToken string `json:\"mfa_token,omitempty\"`\n}\n```\nAuth request/response types (to avoid import cycle with auth package).\n\n```go\ntype LoginResponse struct {\n\tToken     string    `json:\"token\"`\n\tExpiresAt string    `json:\"expires_at\"`\n\tUser      *UserInfo `json:\"user\"`\n\tCSRFToken string    `json:\"csrf_token,omitempty\"`\n}\n```\nLoginResponse carries the JWT token and user summary returned after a successful login.\n\n```go\ntype MFADisableRequest struct {\n\tPassword string `json:\"password\"` //nolint:gosec // G117: intentional credential field in request/response struct -- value is supplied by the authenticated caller or returned once at creation; not re-stored downstream\n\tCode     string `json:\"code\"`\n}\n```\nMFADisableRequest turns off MFA. Requires the current password AND a fresh proof-of-possession (TOTP code or unused recovery code).\n\n```go\ntype MFAEnableRequest struct {\n\tCode string `json:\"code\"`\n}\n```\nMFAEnableRequest finalizes an enrollment by proving the user loaded the secret into their authenticator (the supplied code is validated against the pending secret).\n\n```go\ntype MFAEnableResponse struct {\n\tRecoveryCodes []string `json:\"recovery_codes\"`\n}\n```\nMFAEnableResponse returns the plaintext recovery codes exactly once. Backend stores only bcrypt hashes.\n\n```go\ntype MFARegenerateRequest struct {\n\tCode string `json:\"code\"`\n}\n```\nMFARegenerateRequest replaces all stored recovery codes. Requires a fresh TOTP code (NOT a recovery code — see service for the rationale).\n\n```go\ntype MFARegenerateResponse struct {\n\tRecoveryCodes []string `json:\"recovery_codes\"`\n}\n```\nMFARegenerateResponse mirrors MFAEnableResponse — plaintext codes returned exactly once.\n\n```go\ntype MFASetupRequest struct {\n\tPassword string `json:\"password\"` //nolint:gosec // G117: intentional credential field in request/response struct -- value is supplied by the authenticated caller or returned once at creation; not re-stored downstream\n}\n```\nMFASetupRequest begins an MFA enrollment. Current password is required as defense-in-depth — a stolen session alone shouldn't be enough to swap a user's MFA secret.\n\n```go\ntype MFASetupResponse struct {\n\tSecret          string `json:\"secret\"` //nolint:gosec // G117: intentional credential field in request/response struct -- value is supplied by the authenticated caller or returned once at creation; not re-stored downstream\n\tProvisioningURI string `json:\"provisioning_uri\"`\n}\n```\nMFASetupResponse returns the freshly-generated secret + the otpauth:// URI the frontend renders as a QR code. The secret is already persisted server-side as the pending secret; clients do not need to round-trip it back on enable.\n\n```go\ntype MarketplaceListRequest struct {\n\tPriceSchedule []MarketplacePriceTier `json:\"price_schedule,omitempty\"`\n}\n```\nMarketplaceListRequest is the request body for POST .../marketplace-list. PriceSchedule is optional: when absent the handler computes a default from the row's upfront\\_cost, monthly\\_cost, term, and a 5% discount to attract buyers (documented in the response body so the caller can see what was used).\n\n```go\ntype MarketplaceListResponse struct {\n\tListingID     string                 `json:\"listing_id\"`\n\tListingState  string                 `json:\"listing_state\"`\n\tNote          string                 `json:\"note,omitempty\"`\n\tPriceSchedule []MarketplacePriceTier `json:\"price_schedule\"`\n\tAWSFeePercent float64                `json:\"aws_fee_percent\"`\n}\n```\nMarketplaceListResponse is the JSON response body for a successful listing.\n\n```go\ntype MarketplacePollResult struct {\n\t// Found is the number of listings the run read.\n\tFound int `json:\"found\"`\n\t// Active listings are still for sale on AWS.\n\tActive int `json:\"active\"`\n\t// Settled listings were recorded closed or canceled with their proceeds.\n\tSettled int `json:\"settled\"`\n\t// Unpriced listings were recorded closed or canceled, but some instances\n\t// sold at a price AWS did not identify; they are read again next run.\n\tUnpriced int `json:\"unpriced\"`\n\t// Skipped listings needed no write, or the row changed under the poll\n\t// (canceled, relisted or settled by another run) and the write was dropped.\n\tSkipped int `json:\"skipped\"`\n\t// Errored listings could not be read from AWS or recorded.\n\tErrored int `json:\"errored\"`\n}\n```\nMarketplacePollResult reports one poller run.\n\n```go\ntype MarketplacePriceTier struct {\n\t// TermMonths is the remaining-months count this tier covers.\n\tTermMonths int64 `json:\"term_months\"`\n\t// Price is the USD list price per unit for this tier.\n\tPrice float64 `json:\"price\"`\n}\n```\nMarketplacePriceTier is the JSON-decodable shape accepted in the request body.\n\n```go\ntype OverrideExport struct {\n\tExportedAt time.Time             `json:\"exported_at\"`\n\tOverrides  []OverrideTransferRow `json:\"overrides\"`\n\tVersion    int                   `json:\"version\"`\n}\n```\nOverrideExport is the JSON export document.\n\n```go\ntype OverrideImportReport struct {\n\tSummary map[string]int            `json:\"summary\"`\n\tMode    string                    `json:\"mode\"`\n\tRows    []OverrideImportRowResult `json:\"rows\"`\n\tDryRun  bool                      `json:\"dry_run\"`\n\tApplied bool                      `json:\"applied\"`\n}\n```\nOverrideImportReport is the import response. Applied is true when the insert and update rows were written (never on a dry run, or in strict mode with a rejected row).\n\n```go\ntype OverrideImportRequest struct {\n\tMode      string                `json:\"mode,omitempty\"`\n\tCSV       string                `json:\"csv,omitempty\"`\n\tOverrides []OverrideTransferRow `json:\"overrides,omitempty\"`\n\tDryRun    bool                  `json:\"dry_run,omitempty\"`\n}\n```\nOverrideImportRequest is the POST /api/accounts/service-overrides/import body. Exactly one of Overrides (the JSON export's rows) or CSV (the CSV export's text) is set.\n\n```go\ntype OverrideImportRowResult struct {\n\tAccountID string `json:\"account_id,omitempty\"`\n\tProvider  string `json:\"provider\"`\n\tService   string `json:\"service\"`\n\tAction    string `json:\"action\"`\n\tError     string `json:\"error,omitempty\"`\n\tRow       int    `json:\"row\"`\n}\n```\nOverrideImportRowResult reports what import did, or would do, with one row. Row is 1-based in file order.\n\n```go\ntype OverrideTransferRow struct {\n\tPayment           *string    `json:\"payment,omitempty\"`\n\tUpdatedAt         *time.Time `json:\"updated_at,omitempty\"`\n\tCreatedAt         *time.Time `json:\"created_at,omitempty\"`\n\tRampSchedule      *string    `json:\"ramp_schedule,omitempty\"`\n\tCoverage          *float64   `json:\"coverage,omitempty\"`\n\tEnabled           *bool      `json:\"enabled,omitempty\"`\n\tTerm              *int       `json:\"term,omitempty\"`\n\tService           string     `json:\"service\"`\n\tAccountID         string     `json:\"account_id,omitempty\"`\n\tProvider          string     `json:\"provider\"`\n\tAccountExternalID string     `json:\"account_external_id,omitempty\"`\n\tAccountName       string     `json:\"account_name,omitempty\"`\n\tIncludeEngines    []string   `json:\"include_engines,omitempty\"`\n\tExcludeEngines    []string   `json:\"exclude_engines,omitempty\"`\n\tIncludeRegions    []string   `json:\"include_regions,omitempty\"`\n\tExcludeRegions    []string   `json:\"exclude_regions,omitempty\"`\n\tIncludeTypes      []string   `json:\"include_types,omitempty\"`\n\tExcludeTypes      []string   `json:\"exclude_types,omitempty\"`\n}\n```\nOverrideTransferRow is one account\\_service\\_overrides row in an export or import file (issue #9). The account is named twice: AccountID is the tenant-local UUID, and Provider plus AccountExternalID (AWS account number, Azure subscription, GCP project) identify it portably, so a file exported from one tenant can be imported into another. AccountName, CreatedAt and UpdatedAt are informational: import ignores them.\n\nAn import row is the desired state of the override: an unset field clears that field, unlike the PUT /api/accounts/:id/service-overrides/... merge, which keeps the stored value of any key the body omits. Overrides missing from the file are left alone.\n\n```go\ntype PasswordResetConfirm struct {\n\tToken       string `json:\"token\"`\n\tNewPassword string `json:\"new_password\"`\n}\n```\nPasswordResetConfirm completes a password-reset flow by pairing the one-time token (delivered by email) with the user's chosen new password.\n\n```go\ntype PasswordResetRequest struct {\n\tEmail string `json:\"email\"`\n}\n```\nPasswordResetRequest initiates a password-reset flow by sending a reset link to the provided email address if it matches an existing account.\n\n```go\ntype PatchPlanRequest struct {\n\tName                   *string `json:\"name,omitempty\"`\n\tEnabled                *bool   `json:\"enabled,omitempty\"`\n\tAutoPurchase           *bool   `json:\"auto_purchase,omitempty\"`\n\tNotificationDaysBefore *int    `json:\"notification_days_before,omitempty\"`\n}\n```\nPatchPlanRequest represents a partial update request for plans.\n\n```go\ntype PaymentAdjustment struct {\n\tProvider string `json:\"provider\"`\n\tService  string `json:\"service\"`\n\t// RequestedPaymentOption is the caller's token after trim/lowercase only\n\t// (case-only differences are not surfaced as adjustments, matching the\n\t// operator WARN-log semantics).\n\tRequestedPaymentOption string `json:\"requested_payment_option\"`\n\t// AppliedPaymentOption is the provider-canonical token the purchase will\n\t// actually carry.\n\tAppliedPaymentOption string `json:\"applied_payment_option\"`\n\tReason               string `json:\"reason\"`\n\t// RecIndex is the rec's position in the request's recommendations slice.\n\tRecIndex int `json:\"rec_index\"`\n}\n```\nPaymentAdjustment surfaces a payment-option coercion to the API caller (follow-up to #1503): when the web execute path normalizes a caller-supplied payment option onto a provider-canonical token that bills on a DIFFERENT schedule than what was requested (e.g. Azure \"partial-upfront\" -\u003e \"monthly\"), the response carries one of these per adjusted rec so the caller sees what they requested, what was actually applied, and why, not just the operator WARN log. Purely additive visibility: the coercion policy itself lives in config.NormalizePaymentOption and is unchanged.\n\nCross-provider renames of the SAME schedule (Azure \"all-upfront\" -\u003e \"upfront\", \"no-upfront\" -\u003e \"monthly\") are not adjustments: nothing about the customer's cash flow changed, so there is nothing to disclose. See config.PaymentCoercionChangesSchedule.\n\n```go\ntype Permission struct {\n\tConstraints *PermissionConstraint `json:\"constraints,omitempty\"`\n\tAction      string                `json:\"action\"`\n\tResource    string                `json:\"resource\"`\n}\n```\nPermission represents an action that can be performed on a resource.\n\n```go\ntype PermissionConstraint struct {\n\tAccounts  []string `json:\"accounts,omitempty\"`\n\tProviders []string `json:\"providers,omitempty\"`\n\tServices  []string `json:\"services,omitempty\"`\n\tRegions   []string `json:\"regions,omitempty\"`\n\tMaxAmount float64  `json:\"max_amount,omitempty\"`\n}\n```\nPermissionConstraint limits where a permission applies.\n\n```go\ntype PermissionEntry struct {\n\tAction   string `json:\"action\"`\n\tResource string `json:\"resource\"`\n}\n```\nPermissionEntry is a single {action, resource} pair in the permissions response. Constraints are omitted from the wire shape for now; the frontend uses the pair for UX gating only.\n\n```go\ntype PlanGroupRequest struct {\n\tPayment           *string  `json:\"payment,omitempty\"`\n\tTerm              *int     `json:\"term,omitempty\"`\n\tCoverage          *int     `json:\"coverage,omitempty\"`\n\tMaxStepCommitment *float64 `json:\"max_step_commitment,omitempty\"`\n\tProvider          string   `json:\"provider\"`\n\tService           string   `json:\"service\"`\n\tRecommendationIDs []string `json:\"recommendation_ids\"`\n}\n```\nPlanGroupRequest is one service group of a plan built from selected recommendations. It carries the per-group service settings that a flat plan request sets once at the top level.\n\n```go\ntype PlanHealthFactor struct {\n\tCode    PlanHealthFactorCode `json:\"code\"`\n\tNote    string               `json:\"note\"`\n\tPenalty int                  `json:\"penalty\"`\n}\n```\nPlanHealthFactor is one penalty applied when computing a plan's health score. Returned alongside the score so a bad score is actionable instead of opaque: the frontend tooltip enumerates every factor and its penalty.\n\n```go\ntype PlanHealthFactorCode string\n```\nPlanHealthFactorCode identifies a single scoring factor in a plan's health-score breakdown (issue #340 follow-up). Typed so the frontend tooltip renders deterministic wording per factor instead of parsing free text out of Note.\n\n```go\nconst (\n\tHealthFactorOverdue            PlanHealthFactorCode = \"overdue\"\n\tHealthFactorFailedExecutions   PlanHealthFactorCode = \"failed_executions\"\n\tHealthFactorCanceledExecutions PlanHealthFactorCode = \"canceled_executions\"\n\tHealthFactorRampBlocked        PlanHealthFactorCode = \"ramp_blocked\"\n\tHealthFactorStalled            PlanHealthFactorCode = \"stalled\"\n\tHealthFactorBehindSchedule     PlanHealthFactorCode = \"behind_schedule\"\n\tHealthFactorDisabledMidway     PlanHealthFactorCode = \"disabled_midway\"\n\tHealthFactorStepWillNotAttach  PlanHealthFactorCode = \"step_will_not_attach\"\n)\n```\nHealth-factor codes, in the same order computePlanHealth evaluates them.\n\n```go\ntype PlanPreviewResponse struct {\n\tBaselineOnDemandMonthly *float64          `json:\"baseline_on_demand_monthly\"`\n\tBreakEvenDate           *string           `json:\"break_even_date\"`\n\tFirstExpiry             *string           `json:\"first_expiry\"`\n\tAmountStatus            planAmountStatus  `json:\"amount_status\"`\n\tCurrency                string            `json:\"currency\"`\n\tNote                    string            `json:\"note\"`\n\tSteps                   []PlanPreviewStep `json:\"steps\"`\n}\n```\nPlanPreviewResponse is the body of POST /api/plans/preview.\n\n```go\ntype PlanPreviewStep struct {\n\tAchievedPercent     *float64 `json:\"achieved_percent\"`\n\tMonthlySavings      *float64 `json:\"monthly_savings\"`\n\tOnDemandMonthly     *float64 `json:\"on_demand_monthly\"`\n\tCommitmentMonthly   *float64 `json:\"commitment_monthly\"`\n\tUpfront             *float64 `json:\"upfront\"`\n\tStepCommitmentTotal *float64 `json:\"step_commitment_total\"`\n\tRecurringMonthly    *float64 `json:\"recurring_monthly\"`\n\tNoPurchaseReason    *string  `json:\"no_purchase_reason\"`\n\tHiddenUntil         *string  `json:\"hidden_until\"`\n\tFirstExpiry         *string  `json:\"first_expiry\"`\n\tDate                string   `json:\"date\"`\n\tCumPercent          float64  `json:\"cum_percent\"`\n\tStep                int      `json:\"step\"`\n\tDelayed             bool     `json:\"delayed\"`\n\tHeldSPSkipped       bool     `json:\"held_sp_skipped\"`\n}\n```\nPlanPreviewStep is the state after one step of the previewed plan. Money is null unless the response's amount\\_status is \"ok\".\n\n```go\ntype PlanRequest struct {\n\tTargetCoverage *int `json:\"target_coverage,omitempty\"`\n\t// MaxStepCommitment caps the total commitment one ramp step may\n\t// auto-purchase. Omitted on create = no cap (auto-purchase of steps with\n\t// recommendations stays refused); omitted on update = keep the current cap.\n\tMaxStepCommitment *float64 `json:\"max_step_commitment,omitempty\"`\n\tTerm              *int     `json:\"term,omitempty\"`\n\tPayment           *string  `json:\"payment,omitempty\"`\n\tProvider          string   `json:\"provider,omitempty\"`\n\tService           string   `json:\"service,omitempty\"`\n\tName              string   `json:\"name\"`\n\tRampSchedule      string   `json:\"ramp_schedule,omitempty\"`\n\t// TargetAccounts is read by createPlan only. updatePlan ignores it; account\n\t// assignment on an existing plan goes through setPlanAccounts.\n\tTargetAccounts []string `json:\"target_accounts,omitempty\"`\n\t// Groups builds the plan from selected recommendations, one entry per\n\t// service. It excludes the flat provider/service/term/payment/target_coverage\n\t// fields. createPlan does not read it yet.\n\tGroups                 []PlanGroupRequest `json:\"groups,omitempty\"`\n\tNotificationDaysBefore int                `json:\"notification_days_before\"`\n\tCustomStepPercent      int                `json:\"custom_step_percent,omitempty\"`\n\tCustomIntervalDays     int                `json:\"custom_interval_days,omitempty\"`\n\tAutoPurchase           bool               `json:\"auto_purchase\"`\n\tEnabled                bool               `json:\"enabled\"`\n}\n```\nPlanRequest represents the API request format for creating/updating plans The frontend sends ramp\\_schedule as a string, which we convert to the proper struct.\n\n```go\ntype PlanWithHealth struct {\n\tHealthScore   *int               `json:\"health_score\"`\n\tHealthFactors []PlanHealthFactor `json:\"health_factors,omitempty\"`\n\tconfig.PurchasePlan\n}\n```\nPlanWithHealth wraps a config.PurchasePlan with its computed health-score badge data for the Plans list view (issue #340 follow-up, PR #376). The score/factors are derived at read time from the plan's own attributes and its recent executions -- see computePlanHealth in plan\\_health.go -- and are never persisted, so they can't drift into the config.PurchasePlan struct (and by extension the DynamoDB/Postgres columns backing it).\n\nHealthScore is a pointer so \"not computable\" stays distinguishable from a real score: when the execution counts the score depends on can't be read, the field serializes as null and the UI renders an explicit \"unknown\" badge. Any concrete default would be a fabricated number an operator could not tell apart from a measured one.\n\n```go\ntype PlannedPurchase struct {\n\t// CreatedByUserID is the UUID of the user who created the scheduled\n\t// purchase, mirroring PurchaseHistoryRecord.CreatedByUserID. The\n\t// frontend gates the row action buttons on creator-scope ownership\n\t// (issue #950); omitted for legacy rows with a NULL creator.\n\tCreatedByUserID *string `json:\"created_by_user_id,omitempty\"`\n\tID              string  `json:\"id\"`\n\tPlanID          string  `json:\"plan_id\"`\n\tPlanName        string  `json:\"plan_name\"`\n\tScheduledDate   string  `json:\"scheduled_date\"`\n\tProvider        string  `json:\"provider\"`\n\tService         string  `json:\"service\"`\n\tEstimateNote    string  `json:\"estimate_note,omitempty\"`\n\tResourceType    string  `json:\"resource_type\"`\n\tStatus          string  `json:\"status\"`\n\tRegion          string  `json:\"region\"`\n\tPayment         string  `json:\"payment\"`\n\t// Providers lists a bound plan's group providers (#1746); omitted otherwise.\n\tProviders        []string `json:\"providers,omitempty\"`\n\tCount            int      `json:\"count\"`\n\tUpfrontCost      float64  `json:\"upfront_cost\"`\n\tEstimatedSavings float64  `json:\"estimated_savings\"`\n\tStepNumber       int      `json:\"step_number\"`\n\tTotalSteps       int      `json:\"total_steps\"`\n\tTerm             int      `json:\"term\"`\n\t// HasRecommendations is false for a step that carries no recommendations,\n\t// whose Count, UpfrontCost, EstimatedSavings and ResourceType are then\n\t// placeholders, not data (platform#609).\n\tHasRecommendations bool `json:\"has_recommendations\"`\n\t// Estimate: the figures come from current recommendations, not a stored\n\t// attach; the purchase recomputes them. EstimateNote says why there are none.\n\tEstimate bool `json:\"estimate,omitempty\"`\n}\n```\nPlannedPurchase represents a scheduled purchase from a plan.\n\n```go\ntype PlannedPurchasesResponse struct {\n\tPurchases []PlannedPurchase `json:\"purchases\"`\n}\n```\nPlannedPurchasesResponse holds the list of planned purchases.\n\n```go\ntype PlansResponse struct {\n\tPlans []PlanWithHealth `json:\"plans\"`\n}\n```\nPlansResponse holds the purchase plans response.\n\n```go\ntype PostgresAnalyticsClient struct {\n\t// contains filtered or unexported fields\n}\n```\nPostgresAnalyticsClient implements AnalyticsClientInterface by aggregating the purchase\\_history table. It replaces the legacy S3/Athena-backed client — all purchase history is now written to Postgres and we want the analytics endpoints to serve the same shape without a second storage layer.\n\n```go\nfunc NewPostgresAnalyticsClient(db *database.Connection) *PostgresAnalyticsClient\n```\nNewPostgresAnalyticsClient creates a new Postgres-backed analytics client.\n\n```go\nfunc (c *PostgresAnalyticsClient) QueryBreakdown(\n\tctx context.Context,\n\taccountUUIDs []string,\n\taccountExternalIDsByProvider map[string][]string,\n\tstart, end time.Time,\n\tdimension string,\n) (map[string]BreakdownValue, error)\n```\nQueryBreakdown groups purchase\\_history by dimension (service, provider, region, account) and returns totals + percentage-of-total-savings per bucket.\n\n```go\nfunc (c *PostgresAnalyticsClient) QueryHistory(\n\tctx context.Context,\n\taccountUUIDs []string,\n\taccountExternalIDsByProvider map[string][]string,\n\tprovider string,\n\tstart, end time.Time,\n\tinterval string,\n) ([]HistoryDataPoint, *HistorySummary, error)\n```\nQueryHistory aggregates purchase\\_history rows bucketed by interval. Empty accountUUIDs AND accountExternalIDsByProvider means \"all accounts accessible to the caller\"; scoping is enforced upstream in the handler. A non-empty provider (\"aws\"/\"azure\"/\"gcp\") restricts to rows of that provider; \"\" means all providers (the global-filter \"all\" sentinel is normalised to \"\" in the handler). Returns data points in ascending order and a summary covering the full window.\n\n```go\ntype Principal struct {\n\t// Field order groups the pointer-bearing Session ahead of the trailing\n\t// string so the struct satisfies govet fieldalignment.\n\tKind    PrincipalKind\n\tSession *Session // non-nil when a valid bearer session was presented\n\tUserID  string   // empty for PrincipalAdminAPIKey\n\tEmail   string   // empty for PrincipalAdminAPIKey; populated for session/user-api-key\n\t// APIKeyID is the database ID of the user API key the request\n\t// authenticated with. Non-empty exactly when Kind is\n\t// PrincipalUserAPIKey; empty for every other kind. It lets\n\t// validateSecurityContext book the key's usage once per request without\n\t// re-validating the credential.\n\tAPIKeyID string\n}\n```\nPrincipal carries the resolved caller identity returned by authenticatePrincipal and requireAuth. Handlers that need the caller's identity read it from here rather than re-resolving it through a second ValidateSession / ValidateUserAPIKeyAPI call.\n\n```go\ntype PrincipalKind string\n```\nPrincipalKind identifies which credential type was used to authenticate.\n\n```go\nconst (\n\t// PrincipalAdminAPIKey is set when the request authenticated with the\n\t// shared admin API key (X-API-Key header matching h.apiKey).\n\tPrincipalAdminAPIKey PrincipalKind = \"admin-api-key\"\n\t// PrincipalUserAPIKey is set when the request authenticated with a\n\t// per-user API key issued via /api/api-keys.\n\tPrincipalUserAPIKey PrincipalKind = \"user-api-key\" // #nosec G101 -- credential-type label, not a credential value\n\t// PrincipalSession is set when the request authenticated with a\n\t// bearer-token session (X-Authorization / Authorization header).\n\tPrincipalSession PrincipalKind = \"session\"\n)\n```\n\n```go\ntype ProfileUpdateRequest struct {\n\tEmail           string `json:\"email\"`\n\tCurrentPassword string `json:\"current_password\"`\n\tNewPassword     string `json:\"new_password,omitempty\"`\n}\n```\nProfileUpdateRequest represents a profile update request.\n\n```go\ntype ProviderCoverageSection struct {\n\tOverallCoveragePct *float64             `json:\"overall_coverage_pct\"`\n\tProvider           string               `json:\"provider\"`\n\tServices           []CoverageServiceRow `json:\"services\"`\n}\n```\nProviderCoverageSection is the per-provider block returned by GET /api/inventory/coverage. Services is nil (not \\[]) when the provider has no usage data, which the frontend uses to distinguish \"no usage detected\" from \"usage exists but all services are 0%\". OverallCoveragePct follows the same null-vs-zero contract as CoverageServiceRow.CoveragePct.\n\n```go\ntype PublicInfoResponse struct {\n\tVersion     string `json:\"version\"`\n\tAdminExists bool   `json:\"admin_exists\"`\n}\n```\nPublicInfoResponse holds public information about the CUDly instance. Only fields safe for unauthenticated callers — sensitive identifiers (API key secret URL, deployment AWS account ID) live on the authenticated /api/info/deployment endpoint instead.\n\n```go\ntype PurchaseManagerInterface interface {\n\tApproveExecution(ctx context.Context, execID, token, actor string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)\n\tApproveAndExecute(ctx context.Context, execID, actor string, transitionedBy *string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)\n\t// DirectExecute is ApproveAndExecute for the direct-execute permission; it\n\t// stamps the executed_* audit fields only after the claim is won.\n\tDirectExecute(ctx context.Context, execID, actor string, transitionedBy *string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)\n\t// RunPlannedPurchaseNow forces a pending or paused scheduled purchase to\n\t// execute immediately (the \"Run now\" button), sharing ApproveAndExecute's\n\t// 4-eyes-gated, CAS-guarded funnel instead of a bare status flip that\n\t// nothing else consumes (issue #218).\n\tRunPlannedPurchaseNow(ctx context.Context, execID, actor string, transitionedBy *string, check purchase.ClaimedRowCheck) (*config.PurchaseExecution, string, error)\n\tCancelExecution(ctx context.Context, execID, token, actor string) error\n}\n```\nPurchaseManagerInterface defines purchase manager methods used by handler. \\`actor\\` is the session-authenticated user's email for per-user attribution via the auth-gated deep-link flow; pass \"\" for token-only paths (message workers, legacy callers) where attribution falls back to the notification email at render time.\n\n\\`transitionedBy\\` (ApproveAndExecute) is the session user's UUID stamped onto purchase\\_executions.transitioned\\_by for human-initiated approvals; pass nil for token/system flows so transitioned\\_by = NULL (issue #1009).\n\nApproveExecution, ApproveAndExecute and RunPlannedPurchaseNow return the raw revocation token minted on a successful execute (issue #103: only its hash is stored, so callers can no longer recover a raw, emailable token by re-reading the execution from the store). Empty on failure. All three also return the row with its final status, also on an execution error, and a nil row when the run never started (issue #532).\n\n\\`check\\` (every execute entry point) re-runs the caller's permission Constraints against the row the claim CAS returned, the row that is actually bought, before any provider call (issue #415). The handler's own pre-CAS check reads an earlier snapshot, which a repricing or a recommendation attach can change before the CAS.\n\n```go\ntype RIExchangeConfigResponse struct {\n\tMode                     string  `json:\"mode\"`\n\tUtilizationThreshold     float64 `json:\"utilization_threshold\"`\n\tMaxPaymentPerExchangeUSD float64 `json:\"max_payment_per_exchange_usd\"`\n\tMaxPaymentDailyUSD       float64 `json:\"max_payment_daily_usd\"`\n\tLookbackDays             int     `json:\"lookback_days\"`\n\tAutoExchangeEnabled      bool    `json:\"auto_exchange_enabled\"`\n}\n```\nRIExchangeConfigResponse is the response for GET /api/ri-exchange/config.\n\n```go\ntype RIExchangeConfigUpdateRequest struct {\n\tMode                     string  `json:\"mode\"`\n\tUtilizationThreshold     float64 `json:\"utilization_threshold\"`\n\tMaxPaymentPerExchangeUSD float64 `json:\"max_payment_per_exchange_usd\"`\n\tMaxPaymentDailyUSD       float64 `json:\"max_payment_daily_usd\"`\n\tLookbackDays             int     `json:\"lookback_days\"`\n\tAutoExchangeEnabled      bool    `json:\"auto_exchange_enabled\"`\n}\n```\nRIExchangeConfigUpdateRequest is the request body for PUT /api/ri-exchange/config.\n\n```go\ntype RIExchangeHistoryResponse struct {\n\tRecords []config.RIExchangeRecord `json:\"records\"`\n\t// DirectExecutions lists the interactive (direct) exchanges, which live in\n\t// ri_exchange_direct_executions rather than ri_exchange_history (#1883).\n\tDirectExecutions []riExchangeDirectHistoryItem `json:\"direct_executions\"`\n}\n```\nRIExchangeHistoryResponse is the response for GET /api/ri-exchange/history.\n\n```go\ntype RIUtilizationResponse struct {\n\tUtilization []riUtilization `json:\"utilization\"`\n}\n```\nRIUtilizationResponse holds per-RI utilization data.\n\n```go\ntype RateLimitConfig struct {\n\tMaxAttempts int           // Maximum number of attempts allowed\n\tWindowSecs  int           // Time window in seconds\n\tWindow      time.Duration // Computed time window (for convenience)\n}\n```\nRateLimitConfig defines the rate limiting parameters for a specific endpoint/operation.\n\n```go\nfunc NewRateLimitConfig(maxAttempts, windowSecs int) RateLimitConfig\n```\nNewRateLimitConfig creates a new RateLimitConfig.\n\n```go\ntype RateLimiterInterface interface {\n\t// Allow checks if a request should be allowed based on rate limits\n\t// Returns (allowed bool, error)\n\tAllow(ctx context.Context, key string, endpoint string) (bool, error)\n\n\t// AllowWithIP is a convenience method for IP-based rate limiting\n\tAllowWithIP(ctx context.Context, ip string, endpoint string) (bool, error)\n\n\t// AllowWithEmail is a convenience method for email-based rate limiting\n\tAllowWithEmail(ctx context.Context, email string, endpoint string) (bool, error)\n\n\t// AllowWithUser is a convenience method for user-based rate limiting\n\tAllowWithUser(ctx context.Context, userID string, endpoint string) (bool, error)\n}\n```\nRateLimiterInterface defines the interface for rate limiting implementations This allows for both in-memory and database-backed rate limiters.\n\n```go\ntype RecommendationDetailResponse struct {\n\tID               string       `json:\"id\"`\n\tUsageHistory     []UsagePoint `json:\"usage_history\"`\n\tConfidenceBucket string       `json:\"confidence_bucket\"`\n\tProvenanceNote   string       `json:\"provenance_note\"`\n\t// HiddenBy is non-nil when the rec is filtered out by an account-service\n\t// override (issue #214). Each element names one failing dimension:\n\t// \"enabled=false\", \"engine\", \"region\", \"resource_type\" or \"min_count\". The frontend\n\t// renders a \"hidden by your override\" banner when this field is present.\n\t// Absent (null) means the rec is fully visible.\n\tHiddenBy []string `json:\"hidden_by,omitempty\"`\n}\n```\nRecommendationDetailResponse is the per-id payload backing the Recommendations row-click drawer. Contract documented in issue #44.\n\nConfidenceBucket is \"low\" | \"medium\" | \"high\" — server-side mirror of the client-side heuristic that previously lived in frontend/src/recommendations.ts:confidenceBucketFor. Centralizing it server-side lets future provider-specific tuning happen in one place.\n\nProvenanceNote is a short human-readable string naming the collector + the freshness window. Rendered verbatim in the drawer.\n\n```go\ntype RecommendationsResponse struct {\n\t// NextCursor is set only on a paginated request (limit or cursor sent)\n\t// that has more rows; pass it back as ?cursor= for the next page.\n\tNextCursor      string                        `json:\"next_cursor,omitempty\"`\n\tRecommendations []config.RecommendationRecord `json:\"recommendations\"`\n\tRegions         []string                      `json:\"regions\"`\n\tSummary         RecommendationsSummary        `json:\"summary\"`\n}\n```\nRecommendationsResponse holds the recommendations response.\n\n```go\ntype RecommendationsSummary struct {\n\tTotalCount          int     `json:\"total_count\"`\n\tTotalMonthlySavings float64 `json:\"total_monthly_savings\"`\n\tTotalUpfrontCost    float64 `json:\"total_upfront_cost\"`\n\tAvgPaybackMonths    float64 `json:\"avg_payback_months\"`\n}\n```\nRecommendationsSummary holds aggregate statistics for recommendations.\n\n```go\ntype RefreshResponse struct {\n\tStartedAt       time.Time  `json:\"started_at\"`\n\tLastCollectedAt *time.Time `json:\"last_collected_at\"`\n}\n```\nRefreshResponse is the 202 body returned by POST /api/recommendations/refresh. started\\_at is the timestamp recorded by MarkCollectionStarted. last\\_collected\\_at is the previous successful collection timestamp (may be nil on first-ever collection). The frontend polls GET /api/recommendations/freshness every 5 s and clears the refreshing banner once last\\_collected\\_at advances past started\\_at.\n\n```go\ntype RegistrationRequest struct {\n\tProvider            string `json:\"provider\"`\n\tExternalID          string `json:\"external_id\"`\n\tAccountName         string `json:\"account_name\"`\n\tContactEmail        string `json:\"contact_email\"`\n\tDescription         string `json:\"description\"`\n\tSourceProvider      string `json:\"source_provider\"`\n\tAWSRoleARN          string `json:\"aws_role_arn\"`\n\tAWSAuthMode         string `json:\"aws_auth_mode\"`\n\tAWSExternalID       string `json:\"aws_external_id\"`\n\tAzureSubscriptionID string `json:\"azure_subscription_id\"`\n\tAzureTenantID       string `json:\"azure_tenant_id\"`\n\tAzureClientID       string `json:\"azure_client_id\"`\n\tAzureAuthMode       string `json:\"azure_auth_mode\"`\n\tGCPProjectID        string `json:\"gcp_project_id\"`\n\tGCPClientEmail      string `json:\"gcp_client_email\"`\n\tGCPAuthMode         string `json:\"gcp_auth_mode\"`\n\tGCPWIFAudience      string `json:\"gcp_wif_audience\"`\n\tCredentialType      string `json:\"credential_type\"`\n\tCredentialPayload   string `json:\"credential_payload\"`\n}\n```\nRegistrationRequest is the JSON body for POST /api/register.\n\n```go\ntype RegistrationStatusResponse struct {\n\tStatus          string `json:\"status\"`\n\tCreatedAt       string `json:\"created_at\"`\n\tRejectionReason string `json:\"rejection_reason,omitempty\"`\n}\n```\nRegistrationStatusResponse is the limited public response for GET /api/register/:token.\n\n```go\ntype RejectRequest struct {\n\tReason string `json:\"reason\"`\n}\n```\nRejectRequest is the JSON body for POST /api/registrations/:id/reject.\n\n```go\ntype ReshapeRecommendationsResponse struct {\n\tRecsCollectedAt *time.Time                       `json:\"recs_collected_at,omitempty\"`\n\tRecsStaleness   string                           `json:\"recs_staleness,omitempty\"`\n\tRecommendations []exchange.ReshapeRecommendation `json:\"recommendations\"`\n\t// ExcludedRIs lists RIs left out of cost-based analysis (and so have no\n\t// recommendation) because their monthly cost could not be computed.\n\tExcludedRIs []ExcludedRI `json:\"excluded_ris,omitempty\"`\n}\n```\nReshapeRecommendationsResponse holds reshape recommendations.\n\nRecsStaleness is empty when the underlying Cost Explorer cache is fresh, \"soft\" when it is older than reshapeSoftStaleThreshold (12 h), and \"hard\" when it is older than reshapeHardStaleThreshold (24 h). RecsCollectedAt carries the raw timestamp so the frontend can build its own relative-time label (\"last collected 23h ago\").\n\n```go\ntype Route struct {\n\tHandler    RouteHandler\n\tExactPath  string\n\tPathPrefix string\n\tPathSuffix string\n\tMethod     string\n\tAuth       AuthLevel\n}\n```\nRoute defines a routing rule.\n\n```go\ntype RouteHandler func(ctx context.Context, req *events.LambdaFunctionURLRequest, params map[string]string) (any, error)\n```\nRouteHandler is a function that handles a matched route.\n\n```go\ntype Router struct {\n\t// contains filtered or unexported fields\n}\n```\nRouter manages request routing.\n\n```go\nfunc NewRouter(h *Handler) *Router\n```\nNewRouter creates a new router with all routes configured. Panics on startup if any route was registered with an unset Auth field — see the AuthLevel doc for the rationale (forces every route author to declare a level explicitly so a missed field can't silently inherit an over- or under-permissive default).\n\n```go\nfunc (r *Router) Route(ctx context.Context, method, path string, req *events.LambdaFunctionURLRequest) (any, error)\n```\nRoute finds and executes the matching route handler.\n\nAuthentication enforcement is defense-in-depth: authentication middleware already runs in the middleware pipeline before dispatch, but Router.Route also enforces the per-route Auth level so routes stay protected even if middleware ordering changes or a new code path bypasses validateSecurityContext. AuthAdmin routes require admin access; AuthUser routes require any authenticated user; AuthPublic routes are unauthenticated. There is no implicit default — every route declares its level at registration time and NewRouter rejects authUnset.\n\n```go\ntype SchedulerInterface interface {\n\tCollectRecommendations(ctx context.Context, ownerToken string) (*scheduler.CollectResult, error)\n\tListRecommendations(ctx context.Context, filter config.RecommendationFilter) ([]config.RecommendationRecord, error)\n\t// ListRecommendationsStrict is ListRecommendations for the money path:\n\t// suppressions and overrides applied, read errors returned (planstep.Source).\n\tListRecommendationsStrict(ctx context.Context, filter config.RecommendationFilter) ([]config.RecommendationRecord, error)\n\t// ScanRecommendations walks the same rows as ListRecommendations in\n\t// byte-wise ID order, chunkSize store rows at a time, calling fn with\n\t// each chunk's survivors (issue #981).\n\tScanRecommendations(ctx context.Context, filter config.RecommendationFilter, chunkSize int, fn func([]config.RecommendationRecord) error) error\n\t// PageRecommendations returns one page of the list and the summary of\n\t// the whole filtered set with every filter evaluated in SQL (issue\n\t// #981). An error wrapping scheduler.ErrRecommendationsPageNeedsScan\n\t// means the request must be served by ScanRecommendations instead.\n\tPageRecommendations(ctx context.Context, scope config.RecommendationListScope, afterID string, limit int) (*config.RecommendationPage, error)\n\t// GetRecommendationByID fetches a single rec by its application-level id,\n\t// bypassing account-override filtering so deep-linked URLs to override-\n\t// hidden recs resolve. hiddenBy is non-nil when the rec would be dropped by\n\t// the override filter; callers render a \"hidden\" banner. Returns nil, nil,\n\t// nil when the rec is absent or fully suppressed.\n\tGetRecommendationByID(ctx context.Context, id string) (rec *config.RecommendationRecord, hiddenBy []string, err error)\n}\n```\nSchedulerInterface defines scheduler methods used by handler.\n\n```go\ntype ServiceSavings struct {\n\tPotentialSavings float64 `json:\"potential_savings\"`\n\tCurrentSavings   float64 `json:\"current_savings\"`\n}\n```\nServiceSavings holds savings data for a service.\n\n```go\ntype Session struct {\n\tUserID string `json:\"user_id\"`\n\tEmail  string `json:\"email\"`\n\t// UserAPIKeyID is the database key ID when the request was authenticated via\n\t// a user API key (not the admin infra key). Empty for bearer-token and\n\t// admin-API-key sessions. Used by requirePermissionConstraints to evaluate\n\t// constraints against the key's effective permissions rather than the owning\n\t// user's full group permissions (adversarial-review F2).\n\tUserAPIKeyID string `json:\"-\"`\n}\n```\nSession holds the minimal identity claims extracted from a validated JWT and attached to the request context by the authentication middleware.\n\n```go\ntype SetupAdminRequest struct {\n\tEmail    string `json:\"email\"`\n\tPassword string `json:\"password\"` //nolint:gosec // G117: intentional credential field in request/response struct -- value is supplied by the authenticated caller or returned once at creation; not re-stored downstream\n}\n```\nSetupAdminRequest is the one-time bootstrap payload used to create the first administrator account when the system has no users yet.\n\n```go\ntype StatusResponse struct {\n\tStatus string `json:\"status\"`\n}\n```\nStatusResponse holds a simple status response.\n\n```go\ntype TargetOfferingsResponse struct {\n\tOfferings []ec2TargetOffering `json:\"offerings\"`\n}\n```\nTargetOfferingsResponse is the response for GET /api/ri-exchange/target-offerings.\n\n```go\ntype TrendsResponse struct {\n\tStart    string                        `json:\"start\"`\n\tEnd      string                        `json:\"end\"`\n\tMonthly  []analytics.MonthlySummary    `json:\"monthly\"`\n\tProvider []analytics.ProviderBreakdown `json:\"by_provider\"`\n\tService  []analytics.ServiceBreakdown  `json:\"by_service\"`\n\tMonths   int                           `json:\"months\"`\n}\n```\nTrendsResponse is the savings-snapshot time-series for the Trends view: a monthly series (coverage %, committed spend, usage, realized savings) plus by-provider and by-service breakdowns over the requested window. Backed by the savings\\_snapshots store / materialized views (issues #1023 / #1033), distinct from the purchase\\_history-backed /history/analytics path.\n\n```go\ntype UpcomingPurchase struct {\n\t// CreatedByUserID propagates the underlying execution's\n\t// created_by_user_id so the dashboard widget can apply the same\n\t// creator-scope ownership gate the Plans page uses (issue #950).\n\t// Without it the widget renders a \"Cancel\" button on every row\n\t// while the backend now 403s for non-owners -- a UX hole that\n\t// surfaces as a confusing toast on click. Mirrors the field on\n\t// PlannedPurchase / PurchaseHistoryEntry. omitempty so legacy\n\t// NULL-creator rows keep the JSON shape they had pre-fix.\n\tCreatedByUserID *string `json:\"created_by_user_id,omitempty\"`\n\tExecutionID     string  `json:\"execution_id\"`\n\tPlanID          string  `json:\"plan_id\"`\n\tPlanName        string  `json:\"plan_name\"`\n\tScheduledDate   string  `json:\"scheduled_date\"`\n\tProvider        string  `json:\"provider\"`\n\tService         string  `json:\"service\"`\n\t// Providers lists a bound plan's group providers (#1746); omitted otherwise.\n\tProviders        []string `json:\"providers,omitempty\"`\n\tStepNumber       int      `json:\"step_number\"`\n\tTotalSteps       int      `json:\"total_steps\"`\n\tEstimatedSavings float64  `json:\"estimated_savings\"`\n\t// HasRecommendations is false for a step that carries no recommendations,\n\t// whose EstimatedSavings is then a placeholder, not data (platform#609).\n\tHasRecommendations bool `json:\"has_recommendations\"`\n}\n```\nUpcomingPurchase represents one upcoming planned purchase — a pending purchase\\_executions row whose scheduled\\_date hasn't fired yet, joined to its parent PurchasePlan for display.\n\nThe dashboard's Cancel button targets ExecutionID via DELETE /api/purchases/planned/{id} (api.deletePlannedPurchase). That cancels THIS scheduled instance and also DISABLES its plan (issue #774; DeletePlannedPurchaseResponse.PlanDisabled reports it): the plan row is kept, but the scheduler creates no further instances until someone re-enables it on the Plans page (issue #312 corrected this comment, which used to say the plan stays active). PlanID is exposed as context (e.g. for linking to the plan's settings) and is NOT what destructive action endpoints should target. PR #207 + #213 history: an earlier iteration routed Cancel to api.deletePlan(planID) which deleted the entire plan; that was too aggressive.\n\n```go\ntype UpcomingPurchaseResponse struct {\n\tPurchases []UpcomingPurchase `json:\"purchases\"`\n}\n```\nUpcomingPurchaseResponse holds upcoming purchase data.\n\n```go\ntype UsagePoint struct {\n\tTimestamp string  `json:\"timestamp\"`\n\tCPUPct    float64 `json:\"cpu_pct\"`\n\tMemPct    float64 `json:\"mem_pct\"`\n}\n```\nUsagePoint is a single sample in the per-recommendation usage time series surfaced by GET /api/recommendations/:id/detail. The series is always ordered by Timestamp ascending. CPUPct/MemPct are 0..100.\n\nEmpty in the current implementation: the collector pipeline does not yet persist time-series utilization per recommendation. The endpoint returns the empty slice with a non-error status so the frontend can render a \"Usage history not yet available\" placeholder rather than a broken empty chart. See known\\_issues/28\\_recommendations\\_detail\\_endpoint.md for the full collector wiring follow-up.\n\n```go\ntype User struct {\n\tID         string   `json:\"id\"`\n\tEmail      string   `json:\"email\"`\n\tCreatedAt  string   `json:\"created_at,omitempty\"`\n\tUpdatedAt  string   `json:\"updated_at,omitempty\"`\n\tGroups     []string `json:\"groups,omitempty\"`\n\tMFAEnabled bool     `json:\"mfa_enabled\"`\n}\n```\nUser is the full user record returned by the admin user-management endpoints. It mirrors UserInfo's identity fields and adds CreatedAt/UpdatedAt audit timestamps; it is never embedded in the public-facing login or session responses, which use the slimmer UserInfo / CurrentUserResponse types instead.\n\n```go\ntype UserInfo struct {\n\tID         string   `json:\"id\"`\n\tEmail      string   `json:\"email\"`\n\tGroups     []string `json:\"groups,omitempty\"`\n\tMFAEnabled bool     `json:\"mfa_enabled\"`\n}\n```\nUserInfo is a lightweight projection of the authenticated user included in login and session responses; it carries only the fields needed for client-side routing and display, without exposing credential hashes or internal audit fields.\n\n```go\ntype UserPermissionsResponse struct {\n\tPermissions               []PermissionEntry `json:\"permissions\"`\n\tIsAdmin                   bool              `json:\"is_admin\"`\n\tUnrestrictedAccountAccess bool              `json:\"unrestricted_account_access\"`\n}\n```\nUserPermissionsResponse is the response shape for GET /api/auth/me/permissions. Permissions is the caller's effective set: for a user session, the union of the user's groups; for a user API key, the key's permissions intersected with its owner's (issue #62); for the admin API key, {admin, \\*}. IsAdmin mirrors whether that effective set contains the {admin, \\*} wildcard. UnrestrictedAccountAccess reports whether the caller's account scope covers every account, which global actions such as POST /api/recommendations/refresh require (issue #619). Like the permission entries it is for UX gating only; the backend still enforces the scope.\n\n```go\ntype VersionResponse struct {\n\tVersion   string `json:\"version\"`\n\tGitSHA    string `json:\"git_sha\"`\n\tBuildTime string `json:\"build_time\"`\n}\n```\nVersionResponse holds build-identity metadata for the public /version endpoint. It carries no sensitive data (no account IDs, ARNs, or secrets) so it is safe to expose unauthenticated. The fields let an operator curl a running environment and compare git\\_sha against the branch HEAD to diagnose deploy-lag (an environment still serving a stale build).\n\n","path":"github.com/LeanerCloud/cloud-commitments-platform/internal/api","name":"api","synopsis":"Package api provides the HTTP API handlers for the CUDly dashboard.","isRedistributable":true}
