惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
aimingoo的专栏
aimingoo的专栏
Y
Y Combinator Blog
Vercel News
Vercel News
Blog — PlanetScale
Blog — PlanetScale
有赞技术团队
有赞技术团队
P
Proofpoint News Feed
WordPress大学
WordPress大学
V
V2EX
The Register - Security
The Register - Security
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
D
DataBreaches.Net
G
Google Developers Blog
O
OpenAI News
S
Schneier on Security
Simon Willison's Weblog
Simon Willison's Weblog
I
Intezer
Engineering at Meta
Engineering at Meta
Recorded Future
Recorded Future
T
Threatpost
The Hacker News
The Hacker News
Cisco Talos Blog
Cisco Talos Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
B
Blog RSS Feed
Apple Machine Learning Research
Apple Machine Learning Research
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 热门话题
G
GRAHAM CLULEY
博客园 - 叶小钗
V
Vulnerabilities – Threatpost
云风的 BLOG
云风的 BLOG
L
LINUX DO - 最新话题
MyScale Blog
MyScale Blog
L
LangChain Blog
Scott Helme
Scott Helme
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
Google Online Security Blog
Google Online Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
N
News | PayPal Newsroom
NISL@THU
NISL@THU
M
MIT News - Artificial intelligence
Cloudbric
Cloudbric
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Cloudflare Blog
Recent Announcements
Recent Announcements

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Two days chasing a SharedKey signature mismatch: fixing azurerm_storage_table_entity in Topaz
Kamil Mrzygł · 2026-04-30 · via DEV Community

Some bugs announce themselves loudly. A null pointer in a hot path, a missing route that returns 404 to every request — the kind of thing that fails immediately and points straight at the cause. Others are quieter. They let most of the stack work correctly and only reveal themselves at the intersection of two independently correct but mutually incompatible assumptions. The azurerm_storage_table_entity failure was the second kind.

This post is an account of a two-day investigation into a persistent 401 Unauthorized response on Terraform table entity operations, the four separate bugs we found along the way, and how pairing with GitHub Copilot shaped the investigation. The fix touched authentication, HTTP routing, upsert semantics, and stream lifecycle — each uncovered only after the previous one was resolved.

You can read more about Topaz here: https://topaz.thecloudtheory.com/

The starting point

Topaz already had table storage support: accounts, tables, entity insert and query. The azurerm_storage_table Terraform resource worked. What did not work was azurerm_storage_table_entity. Any Terraform run that tried to create a table entity failed immediately:

Error: creating Entity (Partition Key "pk1" / Row Key "rk1" / ...):
  executing request: unexpected status 401 (401 Unauthorized) with EOF

Enter fullscreen mode Exit fullscreen mode

The 401 was puzzling because the same storage account, created by the same Terraform run, authenticated correctly for every ARM-level operation. Listing keys worked. Creating the table worked. Only the data-plane entity operation failed.

The investigation begins: is the key the problem?

The first hypothesis was key mismatch. Terraform calls listKeys to get a storage account key and then uses it to sign data-plane requests with HMAC-SHA256. If Topaz returned a different key than it used to verify the signature, every request would fail.

To confirm or rule this out, we added diagnostic logging across the authentication path. The TableStorageSecurityProvider was modified to emit the full stored keys (as base64 and as raw bytes in hex), the received signature, the computed signature for both keys, the full Authorization header, every request header with its raw bytes, and the exact string-to-sign in hex. ListStorageAccountKeysEndpoint was modified to log a prefix of both keys on every call, so we could correlate what Terraform received with what Topaz verified against.

The first finding was that the keys were stable. Terraform's listKeys calls (there were four of them per apply — the provider is aggressive about refreshing credentials) consistently received the same key1 prefix. The key logged at verification time matched. The key mismatch hypothesis was eliminated.

Ruling out Topaz restarts

One suspicious pattern appeared in the logs: at a certain point during a test run, ARM requests started returning no route to host on port 8899. This looked like the Topaz container crashing and restarting mid-test — which would regenerate the storage keys and make Terraform's cached key stale.

We checked the Docker container lifecycle carefully. The logs showed two AMQP listener errors at startup (a known benign issue with port reuse in the Docker test environment) but no crash or restart. The no route to host was a red herring — it appeared after Terraform had already failed and was in its cleanup phase, not before. Cross-referencing the listKeys timestamps with the entity request timestamps confirmed: the key prefix was identical across all four calls in the same test run. No restart, no key regeneration.

Narrowing the scope: the isolated test

At this point we were spending time waiting for the full storage batch test to complete — roughly thirty minutes per run because Terraform retries failing requests with exponential backoff before giving up. To eliminate noise from other resources in the same test, we created a minimal isolated scenario: a single resource group, a single storage account, a single table, and a single entity. Nothing else.

resource "azurerm_storage_table_entity" "entity" {
  storage_table_id = azurerm_storage_table.tbl.id
  partition_key    = "pk1"
  row_key          = "rk1"
  entity = {
    name = "isolated-entity"
  }
}

Enter fullscreen mode Exit fullscreen mode

This reduced the iteration cycle and made the logs dramatically easier to read.

The actual bug: URL encoding

With a clean log, the problem became visible. Here is what Topaz logged as the string-to-sign it computed:

GET\n\n\nThu, 30 Apr 2026 06:43:27 GMT\n/tfisoentityacct/isoentities(PartitionKey='pk1',%20RowKey='rk1')

Enter fullscreen mode Exit fullscreen mode

And the TF debug log showed the URL Terraform actually sent the request to:

GET https://tfisoentityacct.table.storage.topaz.local.dev:8890/isoentities%28PartitionKey=%27pk1%27,%20RowKey=%27rk1%27%29

Enter fullscreen mode Exit fullscreen mode

The entity key lookup path contains parentheses and single quotes. Terraform's go-azure-sdk encodes those: (%28, '%27. It signs the request using the raw encoded URL. ASP.NET Core receives the request and makes the decoded path available through HttpRequest.Path. When Topaz called ToString() on that path, it got the decoded form — (PartitionKey='pk1', — which is not what was signed. The HMAC computation was based on a different string than what the client used.

The fix was to read the raw request target before ASP.NET Core's decoding step using IHttpRequestFeature.RawTarget, which preserves the wire-format path exactly as the client sent it:

var rawTarget = context.Features.Get<IHttpRequestFeature>()?.RawTarget
                ?? context.Request.Path.Value
                ?? string.Empty;
var queryIndex = rawTarget.IndexOf('?');
var rawPath = queryIndex >= 0 ? rawTarget[..queryIndex] : rawTarget;

Enter fullscreen mode Exit fullscreen mode

This was a one-line conceptual fix that required updating the IsRequestAuthorized call in all fourteen table endpoint classes. The base class TableDataPlaneEndpointBase was refactored to accept an HttpContext and extract the raw path internally, so all call sites became a single-argument call.

Bug two: the MERGE verb

With auth fixed, the next run reached Terraform's actual entity creation step — and hit a new error:

Request MERGE /isoentities(PartitionKey='pk1',%20RowKey='rk1') has no corresponding endpoint assigned.

Enter fullscreen mode Exit fullscreen mode

The Azure Table Storage REST API uses HTTP MERGE for Insert-or-Merge operations. Topaz's InsertOrMergeTableEntityEndpoint only declared POST in its Endpoints array:

public string[] Endpoints => [@"POST /^.*?\(PartitionKey='.*?',(%20|\s)?RowKey='.*?'\)$"];

Enter fullscreen mode Exit fullscreen mode

Terraform's go-azure-sdk uses MERGE as the verb. The fix was straightforward — add MERGE to the array:

public string[] Endpoints =>
[
    @"POST /^.*?\(PartitionKey='.*?',(%20|\s)?RowKey='.*?'\)$",
    @"MERGE /^.*?\(PartitionKey='.*?',(%20|\s)?RowKey='.*?'\)$",
];

Enter fullscreen mode Exit fullscreen mode

Bug three: Insert-or-Merge semantics

With routing fixed, the next run returned 404 Not Found. The HandleUpdateEntityRequest path calls DataPlane.UpdateEntity, which throws EntityNotFoundException when the entity file does not exist on disk:

if(File.Exists(entityPath) == false)
{
    throw new EntityNotFoundException();
}

Enter fullscreen mode Exit fullscreen mode

For a PUT (Replace) or PATCH (Merge), throwing here is correct — updating a non-existent entity should fail. But MERGE in Table Storage semantics means Insert-or-Merge: create the entity if it does not exist, merge the properties if it does. The existing code had no path for that case.

We added an UpsertEntity method to TableServiceDataPlane that writes a new entity unconditionally, and a upsert parameter to HandleUpdateEntityRequest that catches EntityNotFoundException and falls through to the upsert path:

catch (EntityNotFoundException) when (upsert)
{
    buffered!.Position = 0;
    DataPlane.UpsertEntity(buffered, subscriptionIdentifier, resourceGroupIdentifier,
        tableName, storageAccountName, partitionKey, rowKey);
    response.StatusCode = HttpStatusCode.NoContent;
}

Enter fullscreen mode Exit fullscreen mode

Bug four: the disposed stream

That buffered!.Position = 0 line is significant. The first implementation of the upsert fallback passed the original input stream directly to UpsertEntity. The next test run returned 500 Internal Server Error with Cannot access a disposed object in the Topaz logs.

UpdateEntity reads the body with a StreamReader before throwing EntityNotFoundException. StreamReader disposes its underlying stream by default when it is disposed — which happens when the using var sr block exits after the throw. By the time the catch (EntityNotFoundException) when (upsert) block ran, the stream was already closed.

The fix was to buffer the request body into a MemoryStream before entering the UpdateEntity call when upsert is true, and use leaveOpen: true in UpdateEntity's StreamReader to avoid closing the memory stream on an unexpected throw:

MemoryStream? buffered = null;
if (upsert)
{
    buffered = new MemoryStream();
    input.CopyTo(buffered);
    buffered.Position = 0;
    input = buffered;
}

Enter fullscreen mode Exit fullscreen mode

The test assertion

After all four bugs were fixed, Terraform reported Apply complete! Resources: 4 added, 0 changed, 0 destroyed. The test itself still failed:

System.InvalidOperationException : The node must be of type 'JsonValue'.

Enter fullscreen mode Exit fullscreen mode

The terraform output -json response wraps each output in an envelope: { "partition_key": { "value": "pk1", "type": "string" } }. The initial test assertion called .GetValue<string>() directly on outputs["partition_key"], which is a JsonObject, not a JsonValue. The fix was a one-character change — navigate to ["value"] first, matching every other test in the suite.

The role of Copilot in the investigation

Copilot assisted throughout both days: adding the diagnostic logging, generating the isolated Terraform scenario and test class, and suggesting fixes as each root cause was identified. The investigation benefited from being able to express hypotheses in natural language — "could the key bytes differ even if the base64 strings match?" led immediately to logging the raw bytes in hex — and from having a second reader of the logs who could cross-reference the wire trace in the TF debug log against the canonicalization logic in the Topaz source.

The most valuable contribution was narrowing the investigation down to the URL encoding issue. The logs included a DecodedPathSTS variant that computed the signature using Uri.UnescapeDataString(absolutePath). When that also failed to match, it confirmed the issue was not simply percent-encoded spaces — it was the full encoding of the path characters. Tracing IHttpRequestFeature.RawTarget was the correct escape hatch once the root cause was understood.

What changed

Area Change
TableStorageSecurityProvider Signs against IHttpRequestFeature.RawTarget (raw wire path) instead of HttpRequest.Path (decoded)
InsertOrMergeTableEntityEndpoint Added MERGE verb alongside POST
TableServiceDataPlane Added UpsertEntity; UpdateEntity uses leaveOpen: true
TableDataPlaneEndpointBase HandleUpdateEntityRequest accepts upsert flag; buffers body into MemoryStream for fallback
All 14 table endpoints Updated to pass HttpContext to IsRequestAuthorized

The storage API coverage page now marks azurerm_storage_table_entity create, read, and delete as implemented. The full Terraform scenario — resource group, storage account, table, entity — runs end-to-end in roughly two minutes with no manual steps.

Takeaway

Each of the four bugs was independently plausible and independently fixable. But they were invisible until the previous one was resolved. You cannot see that MERGE is unrouted if you never get past the 401. You cannot see the upsert semantics gap if MERGE returns 404 before reaching the data plane. You cannot see the disposed stream if the upsert path is never exercised. The debugging process was necessarily sequential — each fix revealed the next layer.

The URL encoding issue is worth calling out specifically. The Azure Table Storage SharedKey algorithm requires signing the canonicalized resource, which is derived from the request URL. Whether that URL is in its raw percent-encoded form or its decoded form is not a detail the specification makes obvious. ASP.NET Core's routing infrastructure silently decodes the path before most code ever sees it. IHttpRequestFeature.RawTarget is the correct place to read the unmodified wire path, and it is not the first thing you reach for. Getting there required enough diagnostic signal to rule out every other explanation first.