<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Poshpaws on Medium]]></title>
        <description><![CDATA[Stories by Poshpaws on Medium]]></description>
        <link>https://medium.com/@poshpaws?source=rss-e103b75889b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6fw9dSW0aMwiO04Q</url>
            <title>Stories by Poshpaws on Medium</title>
            <link>https://medium.com/@poshpaws?source=rss-e103b75889b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:44:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@poshpaws/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Gave My GCP Project a Kill Switch So I’d Stop Worrying About the Bill]]></title>
            <link>https://medium.com/@poshpaws/gave-my-gcp-project-a-kill-switch-so-id-stop-worrying-about-the-bill-d7a75f779786?source=rss-e103b75889b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7a75f779786</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Poshpaws]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 07:10:55 GMT</pubDate>
            <atom:updated>2026-08-14T07:10:55.348Z</atom:updated>
            <content:encoded><![CDATA[<p>A Terraform module that disables billing — not your data — the moment a side project’s spend crosses a line you set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4M-5uqAcAnA8VhJ71ZJ0g.png" /></figure><p><strong>The moment that started this</strong></p><p>I was a few hours into a weekend spike — a fridge-photo-to-meal-plan app,<br>the kind of thing you build to see if an idea has legs before you commit to<br>it properly. Scan a photo of your fridge, a vision model figures out what’s<br>in it, another model suggests something to cook, and it exports a shopping<br>list you can tick off in Reminders. Nothing exotic. A Cloud Run service or<br>three, Firestore for storage, Gemini doing the actual thinking.</p><p>It worked. I had it running end-to-end on my phone, hitting a real GCP<br>project, generating real meal suggestions from real fridge photos. And<br>somewhere around the fourth or fifth test scan, a much less exciting<br>thought showed up:</p><p>*What is this actually costing me right now?*</p><p>You know the meme. Guy on a park bench, cardboard sign, “I left an AWS EC2 instance running.” It’s funny because it’s not really about EC2 — it’s<br>about the specific dread of cloud billing, where the meter is running<br>somewhere you can’t see it, denominated in a currency (compute-hours,<br>API calls, egress) you have no intuition for, and the bill arrives *after*<br>the damage is done. You did the thing days ago. You find out about it<br>later, all at once, from an email.</p><p>I wasn’t about to end up on that bench over a fridge app. But the same<br>shape of anxiety was right there in miniature: I went looking for an<br>answer and came up empty. `gcloud` has no command for “tell me what I’ve spent so far” unless you’ve wired up a BigQuery billing export — which I<br>hadn’t, because it was a spike, because who sets up a data warehouse export for a Saturday afternoon project. The Cloud Console has a billing<br>dashboard, but it lags, and it meant leaving the terminal to go stare at a<br>web page hoping the numbers hadn’t done anything alarming.</p><p>I hadn’t spent much. Vertex AI’s Gemini Flash tier is cheap, Cloud Run<br>scales to zero, Firestore for a handful of documents is pennies. But *I<br>didn’t know that* — I was guessing, based on “these services are usually<br>cheap” rather than anything I could point to. And the thing about spikes is<br>they don’t stay small on purpose. You add a feature, you leave a test<br>script running, you forget you turned on a beefier instance type to debug<br>something and never turned it back down. The failure mode isn’t “this<br>service costs money” — it’s “I stopped paying attention and now it’s been<br>running for six days.”</p><p>So I built the thing I actually wanted: a project that turns itself off<br>before that happens.</p><p><strong>The idea</strong></p><p>Not “monitor spend and alert me” — I’d still have to *do* something with<br>the alert, probably while distracted, probably too late. I wanted a hard<br>ceiling. Pick a number. If the project ever spends that much, GCP itself<br>cuts it off. No app code to remember to check, no dashboard to remember to look at, no 3am “why is my card being charged” moment.</p><p>The constraint that made this feel safe to actually use: **it shouldn’t delete anything.** A kill switch that nukes your database the moment you hit a spending cap is a kill switch you’re afraid to arm.</p><p>What I wanted was narrower — stop the *spending*, not the *project*. It turns out GCP has exactly the right primitive for this: you can unlink a project from its billing account.</p><p>Everything that needs billing to run — Cloud Run, Compute Engine, anything metered — stops. Everything that’s just sitting there — Firestore documents, Cloud Storage objects, Artifact Registry images — is untouched. Re-link the billing account and you’re back exactly where youleft off.</p><p><strong>How it actually works</strong></p><p>Four pieces, wired together with Terraform:</p><pre><br>Cloud Billing Budget<br> │ (threshold crossed: 10%, 50%, 100%)<br> ▼<br>Pub/Sub Topic<br> │<br> ▼<br>Cloud Function<br> │ (only acts at 100%)<br> ▼<br>Cloud Billing API → unlink billing account<br></pre><p>A <a href="https://cloud.google.com/billing/docs/how-to/budgets">Billing Budget</a> watches actual spend against a number you set. Every time spend crosses one of your configured thresholds, it publishes a message to a Pub/Sub topic — Google’s own infrastructure does this, no polling required. A Cloud Function subscribed to that topic wakes up on every message. Below 100% of budget, it just logs and exits — those earlier thresholds exist so you *could* wire up a Slack ping or an email if you wanted advance warning, but they don’t trigger anything destructive. At 100%, it does the one thing that matters:</p><pre>@functions_framework.cloud_event<br>def stop_billing(cloud_event: CloudEvent) -&gt; None:<br>    payload = json.loads(base64.b64decode(cloud_event.data[&quot;message&quot;][&quot;data&quot;]))<br><br>    cost_amount = payload.get(&quot;costAmount&quot;, 0)<br>    budget_amount = payload.get(&quot;budgetAmount&quot;, 0)<br>    if cost_amount &lt; budget_amount:<br>        print(f&quot;Spend {cost_amount} below budget {budget_amount} — no action.&quot;)<br>        return<br><br>    client = billing_v1.CloudBillingClient()<br>    info = client.get_project_billing_info(name=_PROJECT_NAME)<br>    if not info.billing_enabled:<br>        print(&quot;Billing already disabled — no action.&quot;)<br>        return<br><br>    client.update_project_billing_info(<br>        name=_PROJECT_NAME,<br>        project_billing_info=billing_v1.ProjectBillingInfo(billing_account_name=&quot;&quot;),<br>    )<br>    print(f&quot;Cost cap breached ({cost_amount} &gt;= {budget_amount}) — billing disabled.&quot;)</pre><p>Setting `billing_account_name` to an empty string is the unlink operation.<br>That’s genuinely the whole mechanism — no resource deletion API calls, no<br>project shutdown, just severing the one link that lets anything metered<br>keep running.</p><p>Restoring it is a single command, whenever you’re ready:</p><pre>gcloud billing projects link &lt;project_id&gt; - billing-account=&lt;billing_account_id&gt;</pre><p><strong>The gotcha that actually cost me an hour</strong></p><p>Everything above worked first try in Terraform, except the budget resource<br>itself, which failed with:</p><p>&gt; Your application is authenticating by using local Application Default<br>&gt; Credentials. The billingbudgets.googleapis.com API requires a quota<br>&gt; project, which is not set by default.</p><p>I’d authenticated Terraform with `gcloud auth application-default login` — <br>completely standard for local dev. Setting the quota project the obvious<br>way (`gcloud auth application-default set-quota-project &lt;project&gt;`) didn’t<br>fix it. Terraform kept sending requests attributed to some other project<br>number entirely — which turned out to be the project number behind<br>gcloud’s own shared OAuth client, not mine.</p><p>The actual fix lives on the provider block, not in `gcloud`:</p><pre>provider &quot;google&quot; {<br> project = var.project_id<br> region = var.region<br> user_project_override = true<br> billing_project = var.project_id<br>}</pre><p>`user_project_override` forces every API call the provider makes to<br>explicitly bill and quota against your project, overriding whatever the<br>ambient credentials think the quota project should be. Some Google APIs — <br>billing budgets being one of them — apparently don’t respect the ADC quota<br>project setting the way you’d expect, and this is the escape hatch.</p><p>I’m including this because it’s the kind of thing that eats forty minutes<br>and three unhelpful Stack Overflow threads if you hit it cold, and I did.</p><p><strong>Where this doesn’t help</strong></p><p>Worth being honest about the shape of this thing:</p><p>- <strong>**It’s not real-time.** </strong>Billing budget notifications typically land<br> within a few hours of the spend happening, not the instant it happens.<br> This is a backstop for “I left something running and forgot,” not a<br> request-level rate limiter. If you need hard per-request cost control,<br> that’s a different (and much more invasive) problem.<br>- *<strong>*It takes down the whole project.</strong>** If you’ve got unrelated things<br> sharing the project with whatever you’re trying to protect, they go down<br> too. One project per thing you want independently capped.<br>- **<strong>The threshold percentages below 100% don’t do anything on their own</strong>.**<br> They’re notification points you could hook other actions to — I just<br> didn’t need to for this.</p><p>None of that made it less useful for what I actually wanted, which was<br>peace of mind while iterating fast on something disposable.</p><p><strong>Steal it</strong></p><p>I pulled this out of the fridge-planner spike into a standalone Terraform<br>module so I’m not copy-pasting the same four files into every side project<br>I start. It’s on GitHub: [github.com/poshpaws/gcp-billing-killswitch](<a href="https://github.com/poshpaws/gcp-billing-killswitch">https://github.com/poshpaws/gcp-billing-killswitch</a>).</p><pre>module &quot;billing_killswitch&quot; {<br> source = &quot;github.com/poshpaws/gcp-billing-killswitch&quot;<br>project_id = &quot;my-project&quot;<br> name_prefix = &quot;myapp&quot;<br> billing_account_id = &quot;XXXXXX-XXXXXX-XXXXXX&quot;<br> budget_amount = 5<br> budget_currency = &quot;USD&quot;<br>}</pre><p>Five dollars, in my case. Enough to cover genuine experimentation, not<br>enough to lose sleep over.</p><p>The fridge app, for what it’s worth, still works. It correctly identified<br>eggs, spinach, and — memorably — a fairly sad-looking end of a cucumber,<br>and suggested an omelette. The kill switch has never fired. That’s the<br>point — I don’t want the sequel to the EC2 park bench meme to be me,<br>except it’s a guy explaining to strangers that he was rate-limited by<br>Gemini’s food-recognition prompt, not even doing anything cool.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7a75f779786" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your API keys don’t belong in your app binary]]></title>
            <link>https://aws.plainenglish.io/your-api-keys-dont-belong-in-your-app-binary-689fcc2ca574?source=rss-e103b75889b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/689fcc2ca574</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Poshpaws]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 08:38:51 GMT</pubDate>
            <atom:updated>2026-07-21T10:31:11.823Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I moved third-party credentials out of an iOS app and behind a free-tier AWS Lambda, using Apple App Attest — and the three things Apple’s documentation didn’t tell me.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skwSkD5TlYl3di_SwPs-0A.png" /><figcaption>Ship requests , not Creds</figcaption></figure><h3>The problem</h3><p>I was building an iOS app against a third-party data API. The provider did what most providers do: they issued me an OAuth2 client ID, a client secret, and an API key, and left the rest to me.</p><p>The obvious move is to put those credentials in the app. A gitignored Secrets.swift, values injected at build time, never committed. Feels irresponsible.</p><p>Anything compiled into your binary ships to every user’s device, and extracting strings from an IPA requires no jailbreak, no exploit, and no skill:</p><pre>$ unzip MyApp.ipa<br>$ strings Payload/MyApp.app/MyApp | grep -i secret</pre><p>That’s it. Your “secret” is now someone else’s curl script. They can burn through your rate limits, get your credentials revoked, or worse — act as you against the API’s terms of service.</p><p>Obfuscation (XOR-ing the key, splitting it across functions, hiding it in an asset) changes nothing structurally. The app has to reassemble the key to use it, so a debugger attached at the point of use reads it out in plaintext. Obfuscation buys you minutes against a motivated adversary, and the adversary only needs to win once.</p><p>The only structural fix: the credentials never enter the binary at all. They live on a server you control, and the app asks that server to make the call.</p><p>Which immediately raises the harder question — if any app instance can call your proxy, you haven’t protected the keys, you’ve just published a nicer API for them. How does the proxy know a request comes from <em>your genuine app</em> and not from a script that read your endpoint out of the same binary?</p><h3><strong>The constraints</strong></h3><ul><li>No user accounts. This app deliberately has none, and bolting on sign-in purely to protect an API key is hostile to users.</li><li>Effectively zero cost. Personal app, low traffic. The proxy must live inside AWS’s <em>permanent</em> free tier — not the 12-month new-account trial.</li><li>Industry-standard auth. No home-brew HMAC scheme with a “secret” that’s just another string in the binary (that moves the problem, it doesn’t solve it).</li></ul><p>The industry-standard answer for “prove this is a genuine instance of my app on genuine hardware, without a user identity” is Apple App Attest.</p><h3>App Attest in one minute</h3><p>App Attest is part of Apple’s <a href="https://developer.apple.com/documentation/devicecheck">DeviceCheck framework</a>, and you reach it through a single class: <a href="https://developer.apple.com/documentation/devicecheck/dcappattestservice">DCAppAttestService</a>. The whole client-side API surface is four calls:</p><ul><li>isSupported — App Attest needs a Secure Enclave, so it&#39;s unavailable in the iOS Simulator and on some older hardware. You must check this and have a fallback story.</li><li>generateKey() — creates a P-256 key pair inside the Secure Enclave and returns a <em>key ID</em> (the SHA-256 hash of the public key). The private key never leaves the hardware — the app can <em>use</em> it, but can&#39;t <em>read</em> it, so it can&#39;t be copied out of the binary the way an embedded API key can.</li><li>attestKey(_:clientDataHash:) — sends the public key to Apple&#39;s servers for certification (see below).</li><li>generateAssertion(_:clientDataHash:) — signs a hash of your request data with the attested key.</li></ul><p>Two operations matter:</p><ol><li>Attestation (once per install): Apple’s servers certify your public key. You get back an attestation object containing an X.509 certificate chain rooted at Apple’s App Attest CA, binding the key to <em>your</em> App ID on genuine hardware. The App ID here is your ten-character team ID plus your bundle ID — ABCDE12345.com.example.myapp — and in App Attest&#39;s WebAuthn-derived vocabulary it plays the role of the Relying Party ID (RP ID): the identifier of the party the credential belongs to. In browser WebAuthn the RP ID is your website&#39;s domain; in App Attest it&#39;s your App ID. It matters because a SHA-256 hash of it is baked into every attestation and every assertion, which is what stops a valid attestation for someone <em>else&#39;s</em> app being registered against your server.</li><li>Assertions (every request): the Secure Enclave signs a hash of your request data with the attested key, alongside a monotonically increasing counter.</li></ol><p>Your server verifies the attestation once, stores the public key, then verifies an assertion on every subsequent call. No Apple API calls needed server-side — it’s all local cryptographic verification, and Apple documents the server-side procedure in <a href="https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server">Validating apps that connect to your server</a>.</p><h3>The architecture</h3><pre>iOS app ──▶ API Gateway (HTTP API, throttled)<br>               └─▶ Lambda (Python, arm64)<br>                      ├─▶ DynamoDB   — attested keys, sign counters, one-time challenges<br>                      ├─▶ SSM Parameter Store — the actual API credentials (SecureString)<br>                      └─▶ Upstream API — called with the real key, server-side only</pre><h3>The flow, end to end</h3><p>The two phases — one-time attestation, then an assertion on every request — look like this across the six parties involved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRRK0Xh__wYXSx_CAa50gQ.png" /></figure><p>Note who talks to whom. Apple is only involved once, at attestation time, and only ever from the <em>device</em> — the server never calls Apple. And the Secure Enclave never sees the network at all: the app brokers everything, but the private key stays in hardware on the other side of that boundary.</p><p>Everything fits the permanent free tier: Lambda (1M requests/month free, forever), API Gateway HTTP API (pennies at personal scale), DynamoDB <em>provisioned</em> at 1 RCU/1 WCU — the important detail being that provisioned capacity has a permanent 25/25 free allowance while on-demand only has a 12-month trial — and SSM Standard parameters, which are free.</p><p>Priced with Infracost: £0.00/month.</p><h3>Verifying an attestation, properly</h3><p>This is the part with teeth. The attestation object is <a href="https://cbor.io/">CBOR</a> — Concise Binary Object Representation (<a href="https://www.rfc-editor.org/rfc/rfc8949">RFC 8949</a>), a binary serialisation format with a JSON-like data model: maps, arrays, strings, numbers and — crucially, and unlike JSON — raw byte strings, without base64 overhead. It’s the wire format throughout <a href="https://www.w3.org/TR/webauthn-2/">WebAuthn</a>, which is why App Attest, WebAuthn’s cousin, uses it too.</p><p>Where JSON has no standard schema language, CBOR has CDDL — the Concise Data Definition Language (<a href="https://www.rfc-editor.org/rfc/rfc8610">RFC 8610</a>). A CDDL definition describes the shape of a CBOR document the way a type declaration describes a struct, and it’s how Apple specifies the attestation object:</p><pre>attestationObject = {<br>    fmt: &quot;apple-appattest&quot;,<br>    attStmt: {<br>        x5c: [ credCert: bytes, * (caCert: bytes) ],<br>        receipt: bytes<br>    },<br>    authData: bytes<br>}</pre><p>Read it as: a map with three keys — fmt is always the string &quot;apple-appattest&quot;; attStmt holds the certificate chain (x5c: the credential certificate first, then intermediates) and a receipt Apple uses for its own fraud-assessment service; authData is an opaque byte string in WebAuthn&#39;s authenticator-data layout that you parse separately. In Python, one call to the cbor2 library gets you the whole structure:</p><pre>decoded = cbor2.loads(attestation_object)<br># {&quot;fmt&quot;: &quot;apple-appattest&quot;, &quot;attStmt&quot;: {&quot;x5c&quot;: [...], &quot;receipt&quot;: ...}, &quot;authData&quot;: ...}</pre><p>The server must check, in order:</p><ol><li>Certificate chain — the leaf in x5c chains, signature by signature, to Apple&#39;s App Attest root CA, which you pin as a constant in your code (fetch it once from Apple&#39;s PKI page, verify the fingerprint).</li><li>Nonce — compute SHA256(authData ‖ SHA256(challenge)) and compare it against a custom extension in the leaf certificate (OID 1.2.840.113635.100.8.2). This binds the attestation to <em>your</em> one-time challenge — without it, a captured attestation object could be registered again.</li><li>RP ID hash — the first 32 bytes of authData must equal SHA256(&quot;&lt;TeamID&gt;.&lt;BundleID&gt;&quot;) — the hash of your Relying Party ID from earlier. This is what makes the attestation <em>yours</em>: a genuine attestation for any other app fails here, because its authenticator data carries the hash of a different App ID. Get the string wrong (missing team ID, wrong bundle ID, stray whitespace) and every genuine attestation fails the same way, so log the expected hash at startup — it&#39;s the first thing to compare when nothing verifies.</li><li>Counter is zero — a fresh attestation always starts at 0. Non-zero means replay.</li><li>AAGUID environment marker — authData carries either appattest + 7 zero bytes (production) or appattestdevelop (development builds). Check it — otherwise a Debug build&#39;s attestation is indistinguishable from App Store traffic.</li><li>Key ID consistency — the credential ID in authData must equal SHA256(public key), and both must equal the keyId the client claims. This stops a valid attestation being registered under someone else&#39;s key ID.</li></ol><p>Then store the public key in DynamoDB with a conditional put (attribute_not_exists(key_id)) so a key can only ever be registered once.</p><p>For assertions, the critical rule is subtler: take your request parameters from the verified clientData, never from a separate field in the request envelope. The client signs a JSON blob containing the challenge <em>and</em> the actual request payload:</p><pre>let clientData = try JSONSerialization.data(withJSONObject: [<br>    &quot;challenge&quot;: challenge.base64EncodedString(),<br>    &quot;message&quot;: requestPayload,<br>])<br>let clientDataHash = Data(SHA256.hash(data: clientData))<br>let assertion = try await DCAppAttestService.shared.generateAssertion(<br>    keyID, clientDataHash: clientDataHash<br>)</pre><p>If the server verified the signature but then read the payload from an unsigned outer field, a captured assertion for request A could be replayed with request B swapped in. The signature must cover the thing you act on.</p><p>Replay protection is the sign counter: every assertion carries a counter that must be <em>strictly greater</em> than the stored one, advanced with a conditional DynamoDB update so two concurrent requests can’t both pass with the same counter.</p><h3>What the documentation doesn’t tell you</h3><p>Unit tests against synthetic data all passed. The first request from a real iPhone failed. Three times, three different ways — and each failure was a place where Apple’s prose documentation and the bytes coming off real hardware disagree. This is the section I wish I’d been able to read beforehand.</p><h3>1. The nonce extension has an extra layer</h3><p>Apple’s docs describe the leaf certificate extension as containing the nonce. What the DER actually contains is a three-level structure:</p><pre>SEQUENCE<br>  └── [1] context-specific tag (0xA1)<br>        └── OCTET STRING (the 32-byte nonce)</pre><p>I’d implemented the obvious two-level parse — SEQUENCE → OCTET STRING — and every real attestation failed with expected OCTET STRING. The context-specific [1] tag in the middle appears in no Apple documentation I could find. (You can confirm it independently: the pyattest library skips the headers with a hardcoded [6:] slice — three 2-byte TLV headers.)</p><pre>seq = _expect(data, tag=0x30)          # SEQUENCE<br>ctx = _expect(seq, tag=0xA1)           # [1] context-specific — undocumented<br>nonce = _expect(ctx, tag=0x04)         # OCTET STRING</pre><h3>2. The assertion signature is a double hash</h3><p>The docs say the assertion signature is over nonce = SHA256(authenticatorData ‖ clientDataHash). True — but the Secure Enclave signs SHA256(nonce), not nonce directly.</p><p>If you hand your crypto library the nonce as a <em>pre-hashed</em> value:</p><pre>public_key.verify(signature, nonce, ec.ECDSA(Prehashed(SHA256())))  # WRONG</pre><p>…every genuine signature fails. The correct call lets the library apply the second hash:</p><pre>public_key.verify(signature, nonce, ec.ECDSA(SHA256()))  # correct — SHA256(nonce) is signed</pre><p>A genuine double-hash. Invisible in synthetic tests (where you control both sides and make the same mistake twice, consistently), fatal against real hardware.</p><h3>3. Assertion flags lie</h3><p>authenticatorData (a WebAuthn-style structure) has a flags byte, where bit 0x40 means &quot;attested credential data follows&quot;. Real devices set that bit on assertions — where no credential data follows at all. Parse trusting the flag and you crash trying to CBOR-decode zero bytes:</p><pre>cbor2.CBORDecodeEOF: premature end of stream</pre><p>The fix: for assertions, never read past byte 37 (rpIdHash(32) + flags(1) + counter(4)), regardless of what the flags claim. (Again confirmable via pyattest: its assertion parser never inspects the flag at all.)</p><pre>def parse(data, *, expect_credential_data=True):<br>    ...<br>    if expect_credential_data and flags &amp; 0x40:<br>        # only attestations carry credential data — assertions set the<br>        # flag on real hardware without any data following it<br>        aaguid, credential_id, cose_key = _parse_attested_credential_data(data[37:])</pre><p>The meta-lesson: an App Attest implementation that only passes synthetic unit tests is unproven. All three bugs sat behind green test suites. The only test that matters is a real device, a real Secure Enclave, and your server’s logs.</p><h3>What this does and doesn’t protect</h3><p>Worth being honest about the threat model.</p><p>Protected: the API credentials. They exist in SSM Parameter Store, readable only by the Lambda’s execution role, and never appear in any response, log line, or binary. Extracting them via the app is now impossible rather than trivial — the app never has them.</p><p>Protected: the proxy itself, from scripted abuse. No genuine device → no valid assertion → 401. Replayed requests fail the counter check. Captured requests can’t be re-targeted because the signature covers the payload.</p><p>Not protected: a determined attacker running your genuine app on their genuine iPhone can still make requests through the proxy — they’re indistinguishable from a legitimate user, because cryptographically they are one. App Attest proves <em>what</em> is calling, not <em>why</em>. API Gateway throttling caps the blast radius, and that’s the right tool for that job.</p><p>Not protected: Apple rotating the App Attest root CA breaks verification until you redeploy with the new pin. A CloudWatch alarm on Lambda errors is the early-warning signal.</p><p>One more deliberate choice: verification failures return a bare 401 {&quot;error&quot;: &quot;unauthorized&quot;} with the actual reason logged server-side only. Detailed error responses would hand an attacker a verification oracle — a free debugging service for forging requests.</p><h3>The cost of doing it right</h3><p>The whole stack — API Gateway, Lambda, DynamoDB, SSM, CloudWatch — prices at £0.00/month at personal-app scale, permanently, not just for a trial year. The Lambda is ~600 lines of Python (plus the same again in tests), and the client side is one Swift actor of about 80 lines wrapping DCAppAttestService.</p><p>Compare that with the cost of the alternative: credentials revoked after someone scrapes them out of your IPA, and an awkward email to the provider who trusted you with them.</p><p>If you’ve been issued API keys for a mobile app, they don’t belong in the binary. The full working implementation — Lambda, Terraform, tests, and the three hardware-taught fixes above — is on GitHub: <a href="https://github.com/poshpaws/appattest-lambda-proxy">appattest-lambda-proxy</a>.</p><h3>Glossary</h3><ul><li>App Attest — Apple’s service for proving that a request comes from a genuine, unmodified instance of your app on genuine Apple hardware. Part of the DeviceCheck framework.</li><li>DeviceCheck — the Apple framework housing App Attest (via DCAppAttestService) alongside the older per-device token API.</li><li>Secure Enclave — a hardware security module inside Apple silicon, isolated from the main processor. Generates and holds the App Attest private key; keys can be used but never exported.</li><li>Attestation — the one-time ceremony in which Apple certifies a newly generated key pair, producing a CBOR <em>attestation object</em> containing a certificate chain that binds the key to your App ID on genuine hardware.</li><li>Assertion — a per-request signature made with the attested key over a hash of your request data, plus a monotonically increasing counter. What the server verifies on every call after registration.</li><li>Challenge — a random, single-use, server-issued value the client must incorporate into what it signs. Guarantees freshness: a captured attestation or assertion can’t be replayed because its challenge has already been consumed.</li><li>Nonce — in attestation verification, SHA256(authData ‖ SHA256(challenge)), which Apple embeds in the leaf certificate (OID 1.2.840.113635.100.8.2) to bind the certificate to your challenge.</li><li>RP ID (Relying Party ID) — WebAuthn’s name for the identifier of the party a credential belongs to. For App Attest, your App ID: &lt;TeamID&gt;.&lt;BundleID&gt;. Its SHA-256 hash forms the first 32 bytes of every authData.</li><li>App ID — your ten-character Apple team ID joined to your app’s bundle ID, e.g. ABCDE12345.com.example.myapp.</li><li>authenticatorData (authData) — a WebAuthn-defined byte layout: RP ID hash (32 bytes), flags (1 byte), counter (4 bytes), then optionally <em>attested credential data</em> (AAGUID, credential ID, public key). Appears in both attestations and assertions.</li><li>AAGUID — Authenticator Attestation GUID, a 16-byte authenticator identifier inside attested credential data. App Attest uses it as an environment marker: appattest + 7 zero bytes for production, appattestdevelop for development builds.</li><li>Key ID — the SHA-256 hash of the attested public key, used by both client and server to name the key. Also the credential ID inside the attestation’s authData.</li><li>Sign counter — a counter the Secure Enclave increments with each assertion. The server requires it to be strictly greater than the stored value, defeating replay.</li><li>CBOR — Concise Binary Object Representation (RFC 8949), a binary serialisation format with a JSON-like data model plus native byte strings. The encoding of attestation objects and assertions.</li><li>CDDL — Concise Data Definition Language (RFC 8610), the schema language for describing CBOR (and JSON) structures. Apple specifies the attestation object in CDDL.</li><li>COSE — CBOR Object Signing and Encryption (RFC 9052), the CBOR-native encoding used for the public key inside attested credential data.</li><li>DER / ASN.1 — the binary encoding (Distinguished Encoding Rules) of the X.509 certificates in the attestation chain, and of the certificate extension carrying the nonce.</li><li>x5c — the field in the attestation statement holding the X.509 certificate chain: leaf (credential) certificate first, then intermediates, chaining to Apple&#39;s App Attest root CA.</li><li>WebAuthn — the W3C Web Authentication standard. App Attest borrows its data structures (authData, RP ID, attestation formats) wholesale, which is why WebAuthn documentation is often the best reference for App Attest byte layouts.</li><li>Relying party — the WebAuthn term for the server that registers credentials and verifies signatures — in this architecture, the Lambda.</li></ul><h3>Further reading</h3><p>Apple documentation</p><ul><li><a href="https://developer.apple.com/documentation/devicecheck/establishing-your-app-s-integrity">Establishing your app’s integrity</a> — the client-side App Attest guide.</li><li><a href="https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server">Validating apps that connect to your server</a> — the server-side verification steps this article implements.</li><li><a href="https://developer.apple.com/documentation/devicecheck/dcappattestservice">DCAppAttestService</a> — API reference for the four client calls.</li><li><a href="https://www.apple.com/certificateauthority/private/">Apple PKI</a> — where to fetch the App Attest root CA certificate you pin.</li><li><a href="https://developer.apple.com/videos/play/wwdc2021/10244/">WWDC21: Mitigate fraud with App Attest and DeviceCheck</a> — the session that motivates the design.</li></ul><p>Standards</p><ul><li><a href="https://www.rfc-editor.org/rfc/rfc8949">RFC 8949 — CBOR</a> and <a href="https://cbor.io/">cbor.io</a> — the serialisation format.</li><li><a href="https://www.rfc-editor.org/rfc/rfc8610">RFC 8610 — CDDL</a> — the schema language the attestation object is specified in.</li><li><a href="https://www.rfc-editor.org/rfc/rfc9052">RFC 9052 — COSE</a> — the public-key encoding inside authData.</li><li><a href="https://www.w3.org/TR/webauthn-2/">WebAuthn Level 2</a> — the source of the authData layout and attestation vocabulary.</li></ul><p>Libraries</p><ul><li><a href="https://pypi.org/project/cbor2/">cbor2</a> — the Python CBOR decoder used server-s</li><li><a href="https://github.com/dreipol/pyattest">pyattest</a> — an independent Python App Attest implementation, useful for cross-checking undocumented behaviour.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=689fcc2ca574" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/your-api-keys-dont-belong-in-your-app-binary-689fcc2ca574">Your API keys don’t belong in your app binary</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Lambda Durable Functions: Building a “Wait for SSM” Workflow in Python]]></title>
            <link>https://aws.plainenglish.io/aws-lambda-durable-functions-building-a-wait-for-ssm-workflow-in-python-f88435909ab3?source=rss-e103b75889b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f88435909ab3</guid>
            <category><![CDATA[durable-functions]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Poshpaws]]></dc:creator>
            <pubDate>Tue, 05 May 2026 07:52:18 GMT</pubDate>
            <atom:updated>2026-05-05T08:34:38.847Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Rk57FKKmqg2nyj7kQTZsw.png" /><figcaption>Cartoon description of lambda durable function</figcaption></figure><p><em>How to replace a Step Functions state machine with a single check pointed Lambda function</em></p><p>If you’ve ever built a workflow that needs to wait for something — an EC2 instance to register with SSM, an approval to come through, a third-party API to become available — you’ve probably reached for AWS Step Functions. It’s the obvious choice: define your states, add some waits, wire up some tasks, done.</p><p>But what if I told you there’s now a way to write that same workflow as a single Python function, with automatic checkpointing, zero-cost waits, and no state machine JSON to maintain?</p><p>Enter AWS Lambda Durable Functions.</p><p><strong>The Problem</strong></p><p>Here’s a real scenario: when an EC2 instance enters the running state, you need to wait for its SSM agent to come online before running a command on it. The SSM agent can take anywhere from 30 seconds to 15 minutes to register, depending on the AMI, instance type, and how the stars align that day.</p><p>With Step Functions, this looks like:</p><pre>Initialize → Wait 60s → Check EC2 Status → Check SSM → <br>  ├─ Online → Run Command → Done<br>  ├─ Not Ready → Increment Attempt → Wait 60s (loop)<br>  ├─ Instance Stopped → Done<br>  └─ Max Attempts → Done </pre><p>That’s 7+ states, a JSON/ASL definition template, an IAM role for the state machine, another for EventBridge to start it, and the Lambda itself. It works, but it’s a lot of moving parts for what is fundamentally a polling loop which is a bit of an anti-pattern.</p><p>As there is no native support for waiting on SSM command completion via a task token callback — the same pattern used with SQS, ECS, and other integrated services.</p><p>There’s no arn:aws:states:::ssm:sendCommand.waitForTaskToken integration. If you want to send an SSM command and wait for the result, you’re stuck building your own polling loop in ASL: a Wait state, a Lambda to check command status, a Choice state to branch, and a loop-back. At that point, you’ve already lost the “managed orchestration” benefit that justified Step Functions in the first place. You’re writing a bespoke state machine just to poll</p><p><strong>The Durable Functions Alternative<br></strong>With Lambda Durable Functions, the same workflow becomes a single Python file:</p><pre>from __future__ import annotations<br><br>import os<br><br>from aws_durable_execution_sdk_python import (<br>    DurableContext,<br>    durable_execution,<br>    durable_step,<br>)<br>from aws_durable_execution_sdk_python.config import Duration<br><br>WAIT_SECONDS = int(os.environ.get(&quot;WAIT_SECONDS&quot;, &quot;60&quot;))<br>MAX_ATTEMPTS = int(os.environ.get(&quot;MAX_ATTEMPTS&quot;, &quot;10&quot;))<br><br><br>@durable_step<br>def check_instance_running(step_context, instance_id: str) -&gt; bool:<br>    &quot;&quot;&quot;Check if the EC2 instance is still running.&quot;&quot;&quot;<br>    import boto3<br><br>    ec2 = boto3.client(&quot;ec2&quot;)<br>    response = ec2.describe_instance_status(<br>        InstanceIds=[instance_id], IncludeAllInstances=True<br>    )<br>    statuses = response.get(&quot;InstanceStatuses&quot;, [])<br>    if not statuses:<br>        return False<br>    is_running = statuses[0][&quot;InstanceState&quot;][&quot;Name&quot;] == &quot;running&quot;<br>    step_context.logger.info(f&quot;{instance_id} running: {is_running}&quot;)<br>    return is_running<br><br><br>@durable_step<br>def check_ssm_ready(step_context, instance_id: str) -&gt; bool:<br>    &quot;&quot;&quot;Check if the SSM agent is online.&quot;&quot;&quot;<br>    import boto3<br><br>    ssm = boto3.client(&quot;ssm&quot;)<br>    response = ssm.describe_instance_information(<br>        Filters=[{&quot;Key&quot;: &quot;InstanceIds&quot;, &quot;Values&quot;: [instance_id]}]<br>    )<br>    instances = response.get(&quot;InstanceInformationList&quot;, [])<br>    if not instances:<br>        return False<br>    is_online = instances[0].get(&quot;PingStatus&quot;) == &quot;Online&quot;<br>    step_context.logger.info(f&quot;{instance_id} SSM online: {is_online}&quot;)<br>    return is_online<br><br><br>@durable_step<br>def run_command(step_context, instance_id: str) -&gt; dict:<br>    &quot;&quot;&quot;Run a command on the instance via SSM.&quot;&quot;&quot;<br>    import boto3<br><br>    ssm = boto3.client(&quot;ssm&quot;)<br>    response = ssm.send_command(<br>        InstanceIds=[instance_id],<br>        DocumentName=&quot;AWS-RunShellScript&quot;,<br>        Parameters={&quot;commands&quot;: [&quot;echo &#39;Hello from durable Lambda!&#39;&quot;]},<br>    )<br>    command_id = response[&quot;Command&quot;][&quot;CommandId&quot;]<br>    step_context.logger.info(f&quot;Command {command_id} sent to {instance_id}&quot;)<br>    return {&quot;command_id&quot;: command_id, &quot;instance_id&quot;: instance_id}<br><br><br>@durable_execution<br>def handler(event: dict, context: DurableContext) -&gt; dict:<br>    &quot;&quot;&quot;Wait for SSM, then run a command.&quot;&quot;&quot;<br>    instance_id = event[&quot;detail&quot;][&quot;instance-id&quot;]<br><br>    for _attempt in range(MAX_ATTEMPTS):<br>        # Pause for 60 seconds — zero compute cost<br>        context.wait(Duration.from_seconds(WAIT_SECONDS))<br><br>        # Check if instance is still running<br>        running = context.step(check_instance_running(instance_id))<br>        if not running:<br>            return {&quot;status&quot;: &quot;instance_stopped&quot;, &quot;instance_id&quot;: instance_id}<br><br>        # Check if SSM agent is online<br>        ready = context.step(check_ssm_ready(instance_id))<br>        if ready:<br>            result = context.step(run_command(instance_id))<br>            return {&quot;status&quot;: &quot;complete&quot;, **result}<br><br>    return {&quot;status&quot;: &quot;timeout&quot;, &quot;instance_id&quot;: instance_id}</pre><p>That’s it. One file. No state machine definition. No separate IAM roles for orchestration. Let’s break down what’s happening.</p><h3>The Key Concepts</h3><p>@durable_execution — The Entry Point</p><pre>@durable_execution<br>def handler(event: dict, context: DurableContext) -&gt; dict:</pre><p>This decorator replaces the standard Lambda handler pattern. Instead of a regular context object, you get a DurableContext that provides step(), wait(), and other durable operations.</p><p>The critical thing to understand: <strong>your code must be deterministic. </strong>When the function resumes after a wait, Lambda replays your code from the beginning, substituting stored results for completed steps. Don’t generate random numbers or call datetime.now() outside of steps — those will produce different values on replay.</p><p>@durable_step — Check pointed Business Logic</p><pre>@durable_step<br>def check_ssm_ready(step_context, instance_id: str) -&gt; bool:<br>    ...</pre><p>Each @durable_step function:</p><ul><li>Receives a step_context as its first argument (with a logger you should use)</li><li>Gets automatically checkpointed — its return value is saved</li><li>On replay, returns the stored value without re-executing</li><li>Can contain any business logic, including AWS API calls</li></ul><p>The first argument is always step_context. Your actual parameters come after.</p><p>context.step() — Execute a Step</p><pre>running = context.step(check_instance_running(instance_id))</pre><p>This executes the step and creates a checkpoint. If the function is interrupted after this line, the next invocation will skip the step and use the stored result.</p><p>Note the Python SDK is synchronous — no await needed.</p><p>context.wait() — Zero-Cost Pause</p><pre>context.wait(Duration.from_seconds(60))</pre><p>This is the magic. When your function hits a wait():</p><ol><li>Lambda saves the checkpoint log</li><li>The current invocation ends and you stop paying</li><li>After the duration, Lambda invokes your function again</li><li>Your code runs from the top, but completed steps return stored results</li><li>Execution continues from where it left off , in a new invocation Effectively resetting the fifteen minute lambda timer workflows themselves can run up to one year starting and stopping as required and the best bit :</li></ol><p><strong>You’re not paying for a Lambda sitting idle in a </strong><strong>time.sleep() loop. The function literally stops </strong><a href="https://docs.aws.amazon.com/lambda/latest/dg/durable-basic-concepts.html#:~:text=Lambda%20keeps,execution%2E"><strong>running</strong></a><strong>.</strong></p><h3>The Polling Loop Pattern</h3><pre>for _attempt in range(MAX_ATTEMPTS):<br>    context.wait(Duration.from_seconds(WAIT_SECONDS))<br><br>    ready = context.step(check_something(resource_id))<br>    if ready:<br>        result = context.step(do_the_thing(resource_id))<br>        return {&quot;status&quot;: &quot;complete&quot;, **result}<br><br>return {&quot;status&quot;: &quot;timeout&quot;}</pre><p>Each iteration:</p><ol><li>wait() — pauses for N seconds (free)</li><li>step(check) — checkpointed check</li><li>If ready, step(action) — checkpointed action</li><li>If not, loop back</li></ol><p>On each resume after a wait, Lambda replays all completed steps instantly (returning stored values) and continues from the next uncompleted operation.</p><h3>Deploying with Terraform</h3><p>Durable functions need three things beyond a normal Lambda:</p><ol><li>durable_config block — sets execution timeout and retention period</li><li>AWSLambdaBasicDurableExecutionRolePolicy — grants checkpoint permissions</li><li>A published version or alias — durable functions require qualified ARNs</li></ol><pre>resource &quot;aws_lambda_function&quot; &quot;durable&quot; {<br>  function_name = &quot;wait-for-ssm&quot;<br>  role          = aws_iam_role.lambda.arn<br>  handler       = &quot;ssm_thing.handler&quot;<br>  runtime       = &quot;python3.13&quot;<br>  timeout       = 900<br>  filename      = data.archive_file.lambda_zip.output_path<br><br>  durable_config {<br>    # Total time the durable execution can run (not per-invocation)<br>    execution_timeout = 1200  # 20 minutes<br>    retention_period  = 14    # days to keep execution history<br>  }<br>}<br><br># Durable functions require a version/alias<br>resource &quot;aws_lambda_alias&quot; &quot;live&quot; {<br>  name             = &quot;live&quot;<br>  function_name    = aws_lambda_function.durable.function_name<br>  function_version = aws_lambda_function.durable.version<br>}<br><br># Grant checkpoint permissions<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;durable&quot; {<br>  role       = aws_iam_role.lambda.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AWSLambdaBasicDurableExecutionRolePolicy&quot;<br>}</pre><h3>Understanding the Two Timeouts</h3><p>This trips people up:</p><ul><li>Lambda function timeout (max 15 min) — how long each individual invocation can run</li><li>Durable execution timeout (max 1 year) — how long the entire workflow can take</li></ul><p>A durable execution with a 24-hour timeout and a 5-minute Lambda timeout means: each invocation runs for at most 5 minutes, but the workflow can span 24 hours across many invocations. Wait operations don’t count against the Lambda timeout.</p><h3>Gotchas and Lessons Learned</h3><h4>1. Deterministic Code is Non-Negotiable</h4><pre># ❌ Bad — different value on replay<br>timestamp = time.time()<br>context.step(do_something(timestamp))<br><br># ✅ Good — timestamp captured inside the step<br>@durable_step<br>def do_something_with_time(step_context):<br>    timestamp = time.time()<br>    return process(timestamp)</pre><h4>2. Runtime Requirements</h4><p>Durable functions require Python 3.13+ (or Node.js 22+). Python 3.12 and earlier don’t support the durable_config setting. The durable execution SDK is included in the Lambda runtime, but pin it in your deployment package for version consistency.</p><h4>3. STS Credential Expiry</h4><p>As mentioned above, don’t cache cross-account sessions. Each @durable_step runs in a potentially new invocation — get fresh credentials every time.</p><h4>4. Qualified ARNs Only</h4><p>You must invoke durable functions using a version or alias ARN. $LATEST won&#39;t work. This ensures deterministic replay against a fixed code version.</p><h4>5. The Python SDK is Synchronous</h4><p>Unlike the TypeScript SDK which uses async/await, the Python SDK is fully synchronous. No await on context.step() or context.wait().</p><h3>Wrapping Up</h3><p>Lambda Durable Functions are a genuine paradigm shift for workflows that are fundamentally sequential. If your Step Functions state machine is a linear chain of “do thing, wait, check, do next thing,” a durable function will be simpler to write, test, and maintain.</p><p>The key mental model: write normal Python, mark your side effects as @durable_step, and use context.wait() instead of time.sleep(). The SDK handles checkpointing, replay, and resumption.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f88435909ab3" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/aws-lambda-durable-functions-building-a-wait-for-ssm-workflow-in-python-f88435909ab3">AWS Lambda Durable Functions: Building a “Wait for SSM” Workflow in Python</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>