Esmeralda C. Cabrera Ventura ← Articles Dossiers Project details Portfolio LinkedIn
Engineering Dossier Cloud Identity · Event-Driven Operational

Google Cloud OAuth & Nest

An identity-driven, event-based integration joining a closed cloud device to a private local control plane — with no device credentials stored outside Google's identity boundary.

Architecture & Implementation
Esmeralda C. Cabrera Ventura
Cloud Identity Engineering · OAuth 2.0 · Event-Driven Architecture · Hybrid Integration
Scope of this document
A technical account of the identity model, the four-link trust chain across two consoles, the event pipeline that replaced polling, the silent authentication failure and how it was diagnosed structurally, the security and cost posture, and the specified AI control layer that holds no credentials.
Engineering Facts
Live integration · one dedicated Cloud project

Recurring monthly cost$0

OAuth scopes granteddevice interaction only1

Polling loopsall state arrives as pushed events0

Trust chain linksacross three consoles, none validating the others4

Verified checkpointsenablement through rendered device state9

Configured services in the projectCloud Logging and Cloud Pub/Sub2

Compute provisionedno VM, container or functionNone

Observed API request rate~0.013/s
Implied monthly volume~34,000
Pub/Sub free-tier headroom~100×

Inbound ports opened0

The thermostat is the smallest part of this project. What was built is a working instance of a pattern that recurs constantly in enterprise work: a third-party platform holds the data, a private system needs it in real time, and the two are joined through federated identity and asynchronous messaging without opening the perimeter.
01
Thesis

A closed device makes this an identity problem

There is no local API to integrate with, so the only sanctioned route runs through someone else's cloud.

A Google Nest Thermostat has no local HTTP API, exposes no LAN control protocol, and will not respond to anything on the home network. It maintains one outbound relationship, to Google's backend. Any platform that wants to read its temperature or change its setpoint must go through Google, as an authenticated third party, on Google's terms.

Those terms have narrowed. The original partner program was retired, leaving the Smart Device Management API as the only supported route to Nest hardware. Access is not granted by pressing a button on the device: it requires enrolling in a developer program, standing up a Cloud project, registering an OAuth client, creating a second project in a separate Device Access Console, and linking the two so a homeowner's consent grant can be exchanged for tokens scoped to their devices.

That alone would be configuration. The engineering problem is structural: the local control plane runs at a private address behind a residential router, and Google's identity platform will not accept a callback it cannot publicly resolve and verify over TLS. The relying party and the identity provider sit on opposite sides of a boundary that OAuth expects to be continuous.

How do you complete a standards-compliant authorization code flow, and sustain a real-time event stream, between a public identity provider and a private, non-routable service — without exposing that service to the internet?

Objectives, fixed before the build

  • Establish a dedicated Cloud project as the explicit security, billing and API boundary
  • Design an identity layer that grants minimum scope and survives long-lived unattended operation
  • Resolve the redirect-boundary conflict without inbound network exposure
  • Keep device trust in a separate project from cloud resource management
  • Replace polling with an event-driven pipeline delivering changes as they occur
  • Stay inside free-tier consumption, with no recurring subscription
  • Verify every layer independently, against a live system rather than a mock
  • Leave a clean architectural seam for an AI layer that never touches cloud credentials
02
System

Cloud as broker, not as dependency

Google mediates identity and transport; day-to-day automation logic lives locally.

Six components participate, and assigning each a single non-overlapping responsibility is what keeps the trust chain auditable. The device talks only to Google. Google's backend holds authoritative state and emits change events. The Cloud project is the security, billing and API boundary. The Device Access project is the Nest-specific access control layer. Pub/Sub decouples event production from consumption. The local control plane stores the refresh token, consumes events, normalizes them into entities and issues commands.

End-to-end architecture diagram
End to endEverything above the dashed boundary is Google-operated. Everything below the amber box is hardware the operator owns. Two arrows cross between them, both authenticated by one grant.
TechnologyLayerRole in this build
Google Cloud PlatformFoundationDedicated project acting as security, billing and API boundary. Every resource is scoped to it
Smart Device Management APIDevice interfaceThe authoritative and only supported interface for third-party access to device telemetry, state and control
Google Auth PlatformIdentityOAuth 2.0 authorization code flow; external user type promoted to in-production publishing status
OAuth web application clientIdentityRepresents the control plane as a registered relying party, with an exactly matching redirect URI and a rotatable secret
Device Access ConsoleDevice trustBinds the OAuth client to the device scope and enumerates reachable traits; deliberately separate from cloud resource management
Cloud Pub/SubMessagingTopic and subscription carrying device change events, with buffering during consumer downtime
Cloud Monitoring & LoggingObservabilityRequest volume, error conditions and dashboards for the messaging pipeline
Home AssistantControl planeSelf-hosted. Holds credentials, consumes events, normalizes entities and issues authenticated commands
Public redirect bridgeIdentity bridgeA publicly resolvable TLS endpoint satisfying redirect validation, forwarding the response to the private instance

Notable for what is absent

There is no compute in this architecture — no VM, no container, no serverless function. No database, no reverse proxy, no tunnel service, no inbound firewall rule. The integration is assembled entirely from managed identity and messaging primitives plus one piece of local software. Every component removed is a component that cannot fail, cost money or require patching.

Two planes over one trust relationship

The control plane runs from the local instance to Google over the REST API with a bearer token: synchronous, request/response, used for setpoint changes and initial state hydration, with user-visible latency. The telemetry plane runs the other way over a Pub/Sub subscription: asynchronous, push-driven, buffering during local downtime, with no request ever issued on a timer. That split is why the integration is classified as Cloud Push rather than Cloud Polling.

03
Trust

Four links, and none validates the others

A break at any link produces a failure that surfaces somewhere else entirely.

LinkRelationshipEstablished bySymptom if broken
1Cloud project → SDM APIEnabling the service on a billing-enabled projectTokens are valid, every API call is rejected
2Cloud project → OAuth clientA web-application client with an exactly matching redirect URI, external audience, in productionFlow completes on Google's side; no token reaches the relying party
3Device Access project → OAuth clientRegistering the client ID so Google knows which application may request device scopesAuthorization succeeds; the device list comes back empty
4Homeowner → applicationAn interactive consent grant recorded as a partner connection, exchanged for a refresh tokenNo partner connection recorded; no device access at all
Links 1 through 3 are configured in three different consoles. A missing enablement, a mismatched redirect and an unregistered client each fail at a different stage: one at request time, one at callback, one at token exchange.

Three identities, two consoles, three lifecycles

A frequent point of confusion is that three distinct identities are involved. The Cloud project governs billing, API enablement, messaging resources and quota — it answers which services may be called at all. The OAuth client governs application registration, redirect URIs, the secret and consent audience — which application is asking, and where the answer may be sent. The Device Access project governs the binding of client to scope and the set of reachable traits — which devices this application may see.

Conflating them is the most common cause of an integration that authenticates successfully and then returns no devices. The separation is deliberate rather than incidental: cloud resource management and device authorization have different blast radii, so a change to one cannot silently widen the other, and the Device Access project can be revoked outright without disturbing billing, API enablement or any other resource.

04
Privilege

Narrow in three dimensions at once

Scope, project and trait are independent controls, and all three must permit an operation.

The integration requests a deliberately narrow permission set. The primary scope authorizes interaction with enrolled devices and nothing else: no mail, files, contacts, location history or profile data. It cannot be widened after the fact without a fresh consent prompt the homeowner would see. A second scope is requested by the setup flow so the event subscription can be created and consumed on the operator's own project.

Underneath the scope sits trait enumeration. The Device Access project lists the categories it exposes — structure, room, thermostat, camera, doorbell, display — and even with a valid token the application can only reach categories the project surfaces, for devices attached during consent.

Dimension 01
By scope
Device interaction only. A compromised token grants thermostat control, not account access.
Least privilege
Dimension 02
By project
Only devices enrolled in this Device Access project are reachable at all.
Dimension 03
By trait
Only the categories the project exposes. Only thermostat is relevant here; the rest stay unused.
Revocation
Independent
Cutting any one of the three removes access without touching the others.
Verified

Why the authorization code flow, and no other

The integration must act on behalf of a specific homeowner, against their specific devices, over a long period, with no human present to re-authenticate. That eliminates the alternatives cleanly.

Grant typeVerdictReasoning
Client credentialsRejectedAuthenticates an application, not a user. It cannot express "this homeowner consents to this app reaching these devices," which is the entire authorization question
ImplicitRejectedReturns the token through the browser and issues no refresh token. Deprecated, and unusable for unattended long-lived access
Device authorizationRejectedDesigned for input-constrained clients. A full browser UI is available during setup, so the indirection buys nothing
Authorization codeSelectedUser-delegated, exchanges a short-lived code over a back channel, and issues the refresh token that sustains access without further interaction

The setting that decides whether it still works next month

The application was promoted from testing to in-production publishing status. This is easy to mistake for cosmetic and it is a durability requirement: an external application left in testing issues refresh tokens that expire after seven days, which would silently disconnect the device roughly weekly and demand manual re-authorization every time.

The application remains unverified, which is correct here. Verification is the review process for applications requesting sensitive scopes from the general public; this one has an audience of exactly one, stays far under the hundred-user cap, and the only consequence is an interstitial during the one-time consent flow.

05
Boundary

The redirect constraint

The architectural crux, and the source of the failure in section 07.

In the authorization code flow the identity provider returns the code by redirecting the browser to a URI registered in advance. Google validates that URI strictly: for a web application client it must be a publicly resolvable HTTPS endpoint, and the value presented at request time must match the registered value exactly. That is a security property, not a limitation — it is what prevents an attacker redirecting an authorization code to a destination they control.

The local control plane, however, runs at a private address. It is not publicly resolvable, has no valid certificate, and is meaningless outside the local network. It can never be registered as an authorized redirect URI. The two requirements are in direct conflict, and there are exactly two ways to resolve it.

ApproachTrade-offVerdict
Public redirect bridgeA stable, publicly resolvable TLS endpoint that satisfies validation and hands the response back to the local instance. Requires no inbound exposure, but routes the callback through a third-party endpointSelected
Direct callbackKeeps the callback entirely within infrastructure the operator controls, but requires a public hostname with valid TLS — a reverse proxy, certificate management and an inbound firewall ruleAlternative

The bridge was selected because avoiding inbound exposure was a stated objective. The critical detail — and the one that caused the initial failure — is that it only works if the local instance address it forwards to matches the address actually used during setup. When it does not, Google completes the authorization successfully, the browser lands on the bridge, and the handoff silently fails. Nothing errors on Google's side, because from Google's perspective nothing went wrong.

The bridge is a third party in a security-sensitive step. It forwards in the browser rather than server-side and is involved only during setup — but an operator with a public hostname and TLS already in place should prefer the direct callback.

Credential lifecycle

The authorization code lives for seconds and is stored nowhere. The access token lasts about an hour, in memory. The refresh token is long-lived, in local storage, and is the credential that matters. The client secret persists until rotated, and the OAuth client carries two with distinct lifecycles: an original created at registration, and a replacement created two days later, enabled while the original was disabled.

The ordering matters. Creating the new secret while the old one is still enabled leaves a window in which both are valid, so configuration can be updated and verified before the old credential is withdrawn. Disabling first produces an outage. Credential rotation is universally recommended and rarely performed on personal projects; doing it with correct ordering, and disabling the superseded secret rather than abandoning it, is the point.

06
Build

Each layer verified independently

Configuration state proves setup. It does not prove the system works, so every layer is confirmed on its own evidence.

Cloud console audience view with the activity panel showing a billing-blocked enablement and the SDM API enabled
Boundary and enablementOne capture proving three things: billing is enforced before services activate, the device API is enabled, and the consent audience reads zero users of a hundred — the baseline for the grant.
The Smart Device Management API product page confirming enabled state
Verified separatelyA valid token calling a disabled API returns a permission-style error that looks like an OAuth problem. Confirming enablement here eliminates that branch before identity is built.
Device Access project showing bound client, required scope, user limits and traits
Device trustTrust chain link 3: the bound client, the single device scope, the sandbox tier's user limits, and the trait categories the project can surface.
OAuth web application client showing one authorized redirect URI and two client secrets
Client and rotationA single authorized redirect URI, and two secrets — the original disabled, the replacement enabled. The console's own warning about multiple active secrets sits above them.
The same audience page now reading one user of a hundred
Before and afterThe identical page at two points in time. Zero users became one. Server-side evidence of a real consent grant, recorded by Google rather than claimed.
Partner connections view showing an active grant permitting the registered application to manage devices
The fourth link, from the user's sideAlso the revocation control: access granted here can be withdrawn here, independently of either developer console, which is the correct place for that power to sit.
Project dashboard showing sustained request activity with no errors
Live trafficA sustained rate around 0.013 requests per second with no errors. The sawtooth is maintenance cadence, not polling.
Cloud Monitoring integrations filtered to configured, showing two of eighty-five
Minimal footprint, verifiedExactly two integrations configured — logging and messaging. No compute, no database, no incidental services.
The thermostat rendered as a climate entity with temperature and humidity sensors
End to endA 69°F target against 72°F ambient, idle — internally consistent. The discrete sensor preserves half-degree resolution the climate card rounds away, which matters for the next phase.
07
Incident

The silent authentication failure

The first authorization attempt failed in the most instructive way possible: it did not error.

The consent screen appeared, the grant was accepted, the browser redirected — and no token ever arrived. No error banner, no log entry pointing at a cause, nothing on Google's side indicating a problem. That silence is diagnostic in itself, because it eliminates most of the search space immediately.

HypothesisVerdictReasoning
Invalid client credentialsEliminatedThe consent screen rendered. Consent is not displayed for an unrecognized client
Insufficient scopeEliminatedThe screen listed the requested permission and the grant was accepted
API not enabledEliminatedEnablement failures occur at call time, after tokens exist. No token was ever issued
Device not enrolledEliminatedEnrollment problems present as an empty device list after a successful authorization, not as a missing token
Redirect boundary mismatchRoot causeThe only failure mode that completes successfully on the identity provider's side and produces nothing on the relying party's side
Everything before the redirect demonstrably worked and everything after it demonstrably did not. The fault is at the handoff — the one point where responsibility transfers.

The reasoning is structural rather than empirical, which is the part worth carrying forward. Google validates the callback strictly and considers its obligation discharged once it redirects the browser to the registered URI. Whether anything is listening at the other end is not its concern, and not something it can report on.

Resolution

Registering the exact publicly resolvable callback URI on the client, and ensuring the bridge forwards to the same local instance address actually used during setup. The two values must agree: a mismatch in scheme, port, host or trailing slash reproduces the identical silent failure. The incremented user counter is the confirmation that the corrected flow completes.

Failure taxonomy

SymptomLinkRoot causeResolution
Service enablement rejected1No billing account attachedAttach an active billing account, then retry. Consumption may still be zero
API calls rejected despite a valid token1Device API not enabled on the projectEnable it and confirm on the product page
Consent completes, no token arrives2Redirect mismatch or unreachable callback destinationRegister the exact public callback; verify the forwarding target matches the setup address
Explicit redirect mismatch error2Registered URI differs from the one presentedMatch byte for byte, including scheme, port and trailing slash
Disconnection roughly every seven days2Application left in testing publishing statusPromote to in-production status
Token exchange fails at the final step2Wrong OAuth client type registeredUse a web application client; other types apply different redirect rules
Authorization succeeds, no devices returned3Client not bound in the Device Access project, or devices not attached during consentVerify the binding and re-run consent, selecting the devices
Previously working integration stops abruptly3Bound client ID changedChanging it deauthorizes existing tokens. Re-authorize after any such change
Consent lands on the wrong account4Multiple accounts active in the browser sessionComplete the flow in a private window with only the target account signed in

Time-delayed failure modes

The failures that matter most in an unattended system appear weeks or months after a successful build, when the original context is forgotten. Three apply, and all three share one cause: dormancy. Subscriptions are subject to deletion after a period of inactivity, so the integration fails to start because it looks for a subscription that no longer exists. A refresh token unused for about six months has its authorization revoked — and a deployment living on pushed events while rarely calling the API can go stale while appearing healthy, with events arriving right up until the grant lapses. Inactive OAuth clients are likewise subject to deletion.

None produces a warning. None is visible on a dashboard that shows the system working today. Documenting them at build time is what separates a system that was made to work from one designed to keep working.

08
Security

Posture and residual risk

Stated plainly, including the parts that are not ideal.

ControlEffect
Scope minimizationA compromised token grants device interaction, not account access — no mail, files, contacts or location history
Project separationDevice trust lives in a different project from cloud resources; revoking one does not disturb the other
No inbound exposureThe local instance accepts no unsolicited inbound connections. Both cloud paths are outbound-initiated
No device credentials locallyOnly a delegated OAuth refresh token, revocable by the homeowner at any time
Independent revocationAccess can be withdrawn from the partner connections page without touching either developer console
Secret rotationRotated with overlap, superseded credential disabled rather than left active
Minimal attack surfaceNo compute, no database, no reverse proxy, no open ports. Two configured services in the entire project

Residual risk

The redirect bridge. A third party sits in the callback path during one-time setup. It forwards in the browser rather than server-side and is not involved in steady-state operation, but the trade-off was accepted knowingly in exchange for not exposing the local instance inbound.

Local credential storage. The refresh token and client secret live in configuration on the local host, so their security is that host's security. This is inherent to a self-hosted control plane rather than a flaw in the integration, but it makes host hardening, patching and backup encryption load-bearing controls rather than optional hygiene.

Unverified application status. Appropriate for an audience of one, imposing only a consent-time interstitial. It would not be appropriate if the application were ever distributed, and the hundred-user cap is a hard technical boundary on that, not merely a policy one.

The dominant risk is not the cloud path. It is physical or network compromise of the local host — the same risk any self-hosted platform carries, addressed outside this integration's boundary.
09
Operations

Zero cost, and an observability gap

Real-time capability inside free-tier allowances, and an honest account of what is not yet monitored.

$0
Recurring monthly
~34k
Requests per month
10 GiB
Free message allowance
~100×
Headroom below it

Enrolment in the device access program carries a one-time registration fee, and that is the only unavoidable cost. A billing account must be attached to provision messaging and the device API, but attachment is mandatory while consumption is not. At the observed volume — roughly 34,000 requests a month, with device event messages on the order of one to two kilobytes — monthly message throughput sits well under 100 MB against a 10 GiB free allowance.

The event-driven design is not only cleaner than polling — it is what keeps the cost at zero. Responsiveness and near-zero cost are the same decision here.

Observable, not monitored

Four signals cover the question "is it still working?": the API request rate, error reporting, messaging dashboards, and entity freshness in the control plane. All four are being collected. None of them currently pages anyone.

Three alerting policies would close that: request rate falling to zero over a multi-hour window, unacknowledged message count growing past a small threshold, and subscription age approaching the inactivity horizon. For a residential thermostat the current position is reasonable — the failure is visible on a dashboard and the consequence is inconvenience. It is recorded because the distinction between observable and monitored matters far more in production, and the gap should be named rather than glossed over.

10
Next

An agent that holds no credentials

The delivered system produces the substrate an autonomous layer needs. The design question is what to withhold from it.

What was built is more valuable than a controllable thermostat: a normalized, event-driven, authenticated representation of a physical environment, on hardware the operator controls. The next phase places an AI agent above it as an orchestration layer.

The single most important decision is what the agent is not given. No cloud credentials, no tokens, no client secrets, no direct API access. It interacts exclusively with the local control plane, consuming normalized state and issuing intent-based actions that the control plane executes through its existing authenticated pipeline.

The agent is the lowest-privilege component in the system despite being the highest-level one.

The tempting shortcut is direct API access: fewer moving parts, feels more capable. It is strictly worse on every axis that matters — duplicated credential storage, a bypassed audit trail, coupling to a vendor-specific schema, and a widened blast radius around the component whose behaviour is least predictable. Constraining the agent costs nothing in capability and leaves the established security model completely intact.

GuardrailPurpose
Absolute setpoint boundsHard minimum and maximum enforced by the control plane. No reasoning path can produce a target outside the safe range
Rate limitingA floor on the interval between changes, preventing oscillation and protecting equipment from short-cycling
Confirmation for high-impact actionsLarge deviations or extended schedule changes require explicit approval rather than executing autonomously
Dry-run modeThe agent proposes without executing during an evaluation period, so its judgement can be assessed before it is trusted
Full audit logEvery action recorded with its reasoning, enabling retrospective review
Manual override precedenceA human adjustment always wins and suspends agent control for a defined window
A guardrail the agent enforces on itself fails whenever the agent misbehaves — which is precisely the condition it exists to handle. Bounds checked at the point of execution hold regardless of what the reasoning layer concludes.
ObjectiveStateEvidence
Dedicated Cloud project as security and billing boundaryDeliveredBilling enforcement and minimal footprint
Device API enabled as the authoritative interfaceDeliveredEnablement event and product page confirmation
Identity layer durable for unattended operationDeliveredIn-production status and registered client
Redirect boundary conflict resolvedDeliveredRegistered redirect URI; user counter increment
Device trust isolated in a separate projectDeliveredClient binding, scope and traits
Polling replaced with event-driven messagingDeliveredMessaging configured; request profile
Zero recurring costDeliveredAll consumption within free-tier allowances
Alerting policiesOpenSignals collected; no policy defined yet
AI orchestration layerSpecifiedArchitecture, capability model and guardrails defined
What this build demonstrates

The thermostat is incidental


A single device integration required a full authorization code flow with an external consent audience, cross-console trust delegation between two project types, scope minimization, publish-state management, asynchronous message-queue plumbing, credential rotation and production observability — all validated against a live system rather than a mock.

The pattern is the point: a third-party platform holds the data, a private internal system needs it, and the two must be joined through federated identity and asynchronous messaging without opening the network perimeter. Every technique here transfers directly.


Google Cloud · Smart Device Management API · OAuth 2.0 · Cloud Pub/Sub · Cloud Monitoring & Logging · Home Assistant

Read the article →  ·  All project details  ·  Portfolio & resume  ·  LinkedIn