<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ securityawareness - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ securityawareness - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 22 Nov 2026 12:31:38 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/securityawareness/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Secure by Design: How to Engineer Security into Architecture Before Writing Any Code ]]>
                </title>
                <description>
                    <![CDATA[ There's a conversation that happens in most engineering teams,maybe usually too late. Think of this, a feature ships to production. A security review happens afterwards, or a penetration test finds so ]]>
                </description>
                <link>https://www.freecodecamp.org/news/secure-by-design-engineer-security-into-architecture-before-writing-code/</link>
                <guid isPermaLink="false">6ad05dd81f613b7136df1683</guid>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ securityawareness ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #apisecurity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ OWASP TOP 10 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Design ]]>
                    </category>
                
                    <category>
                        <![CDATA[ System Design ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwaseyi Fatunmole ]]>
                </dc:creator>
                <pubDate>Thu, 15 Oct 2026 05:00:08 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/47f24cb6-f4b9-40eb-9690-db750358c4d6.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There's a conversation that happens in most engineering teams,maybe usually too late.</p>
<p>Think of this, a feature ships to production. A security review happens afterwards, or a penetration test finds something, or worse, an incident report lands in your inbox.</p>
<p>The vulnerability is real. The fix is expensive. And somewhere in the conversation, someone says "we need to add security to this."</p>
<p>That phrase is the problem. Security isn't something you add to software. It's something you build into it from the beginning. The moment you're talking about adding security to something that already exists, you're already in damage control mode.</p>
<p>Secure by Design is a different mindset entirely whereby you define security requirements before you make architecture decisions. You understand the threat model before writing a single class. You identify and enforce business rules at the domain layer. All of these things comes with what engineering has to offer, not a layer that tops up what has been built already.</p>
<p>The CI/CD pipeline catches what human review misses. Every layer of the system is designed with an attacker's perspective in mind, not as an afterthought, but as a foundational requirement.</p>
<p>This isn't a security team's responsibility. It's an engineering team's responsibility. And it starts before the first pull request.</p>
<p>In this handbook, I'll take you through all you need to understand on how your engineering team can cultivate the discipline of having security in mind whilst designing.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#what-secure-by-design-actually-means">What Secure by Design Actually Means</a></p>
</li>
<li><p><a href="#threat-modeling-understanding-your-attack-surface-before-you-build">Threat Modeling: Understanding Your Attack Surface Before You Build</a></p>
</li>
<li><p><a href="#security-as-a-business-rule">Security as a Business Rule</a></p>
</li>
<li><p><a href="#encryption-standards-the-organizational-decision">Encryption Standards: The Organizational Decision</a></p>
</li>
<li><p><a href="#database-security">Database Security</a></p>
</li>
<li><p><a href="#cors-the-boundary-your-api-enforces">CORS: The Boundary Your API Enforces</a></p>
</li>
<li><p><a href="#structured-logging-and-field-level-masking">Structured Logging and Field-Level Masking</a></p>
</li>
<li><p><a href="#cicd-security-gates">CI/CD Security Gates</a></p>
</li>
<li><p><a href="#microservices-and-internal-service-security">Microservices and Internal Service Security</a></p>
</li>
<li><p><a href="#data-privacy-and-compliance-as-engineering-requirements">Data Privacy and Compliance as Engineering Requirements</a></p>
</li>
<li><p><a href="#conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before reading this article, you should be comfortable with:</p>
<ul>
<li><p>Building APIs and backend systems in any language or framework</p>
</li>
<li><p>General software architecture concepts: layers, services, gateways</p>
</li>
<li><p>What CI/CD pipelines are and how they work at a high level</p>
</li>
<li><p>Basic understanding of what encryption and hashing mean</p>
</li>
</ul>
<p>You don't need a security background. This article approaches every concept from an engineering and architecture perspective.</p>
<h2 id="heading-what-secure-by-design-actually-means">What Secure by Design Actually Means</h2>
<p>Secure by Design isn't a checklist. It's not a set of tools you install. It's a way of thinking about software that treats security requirements the same way you treat functional requirements. In this mode of work, you treat your security requirements as things that must be satisfied before the system is considered complete.</p>
<p>Most teams treat security passively. Something breaks, something gets flagged, and something gets patched. The cycle repeats. The system accumulates technical security debt the same way it accumulates any other technical debt, just with higher stakes.</p>
<p>Secure by Design teams treat security proactively. Before a feature is built, the engineering team asks: what are the threats against this feature? Where is the data sensitive? What happens if an attacker controls this input? What is the blast radius if this component is compromised? The answers shape the architecture, not the other way around.</p>
<p>This produces fundamentally different systems. Not because the individual components are different, but because the design decisions at every layer reflect an understanding of what can go wrong.</p>
<p>Perfect instances are as follows :<br>The API gateway rate-limits by default because the design accounted for abuse.<br>The domain layer enforces business rules because the design identified where those rules belong.<br>The CI/CD pipeline catches secrets in code because the design included that gate from the start. etc</p>
<p>The cost of getting security right at design time is a fraction of the cost of trying to fix or manage it. And the cost of managing it is a fraction of the cost of a major incident. Its just a matter of time!</p>
<h2 id="heading-threat-modeling-understanding-your-attack-surface-before-you-build">Threat Modeling: Understanding Your Attack Surface Before You Build</h2>
<p>Threat modeling is the process of systematically identifying what can go wrong with a system before it's built. It's a formal engineering activity, not a security team exercise.</p>
<p>The goal is simple: understand who might attack your system, what they might want, how they might try to get it, and what the impact would be if they succeeded. With that understanding, you make deliberate design decisions that reduce the likelihood and impact of those attacks.</p>
<h3 id="heading-the-four-questions-of-threat-modeling">The Four Questions of Threat Modeling</h3>
<p><strong>1. What are we building?</strong></p>
<p>This particular usecase starts by mapping the system. What are the components? How do they communicate? Where does data flow? Where are the trust boundaries, the points where data crosses from one context of trust to another?</p>
<p>A trust boundary exists between your API gateway and the internet, between your service layer and the database, and between your system and a third-party integration. Every trust boundary is a potential attack surface.</p>
<p>Here you have to draw the data flow, map every place where data enters the system, where it's stored, where it's processed, and where it leaves. This gives you a complete picture of what you're protecting.</p>
<p><strong>2. What can go wrong?</strong></p>
<p>In this usecase, you ask for each component and each data flow, what can an attacker do. Here comes <strong>STRIDE.</strong> This is an acronymn of laid down questions that helps fulfil this particular usecase.</p>
<ul>
<li><p><strong>Spoofing:</strong> Can an attacker pretend to be someone they're not? Can they forge a token, impersonate a user, or claim an identity they don't own?</p>
</li>
<li><p><strong>Tampering:</strong> Can an attacker modify data in transit or at rest? Can they change a transaction amount, modify a callback payload, or alter a stored record?</p>
</li>
<li><p><strong>Repudiation:</strong> Can a user deny having performed an action? Are there sufficient audit logs to prove what happened, when, and by whom?Can we prove that a user performed am action on the system?</p>
</li>
<li><p><strong>Information Disclosure:</strong> Can an attacker learn something they shouldn't? Can they read another user's data, extract internal system information from error responses, or discover internal infrastructure details from stack traces?</p>
</li>
<li><p><strong>Denial of Service:</strong> Can an attacker prevent legitimate users from accessing the system? Can they exhaust resources, trigger expensive operations, or overwhelm the system with traffic?</p>
</li>
<li><p><strong>Elevation of Privilege:</strong> Can an attacker gain permissions they weren't granted? Can a regular user access admin functions, or can an external caller reach internal APIs?</p>
</li>
</ul>
<p><strong>3. What are we going to do about it?</strong></p>
<p>For each identified threat, we decide on a countermeasure. Mitigate it by reducing the likelihood or impact. Transfer it by using a managed service that handles it. Accept it if the risk is genuinely low and the mitigation cost is too high. Eliminate it by changing the design so the threat no longer applies.</p>
<p>The decision is explicit and documented. Not implicit or <a href="http://assumed.It">assumed.It</a> must be documented.</p>
<p><strong>4. Did we do a good enough job?</strong></p>
<p>After the system is built, verify that the countermeasures were actually implemented. Threat modeling is a living document, not a one-time exercise. When the system changes, the threat model must be revisited.</p>
<h3 id="heading-what-threat-modeling-produces">What Threat Modeling Produces</h3>
<p>A threat model produces two things that are genuinely valuable: a list of security requirements that must be satisfied before the system ships, and an understanding of where the high-risk areas are, so engineering effort is focused correctly.</p>
<p>Without a threat model, security is applied uniformly and often superficially. Every component gets the same level of attention regardless of its actual risk level. With a threat model, you know which components are high-risk, which data flows are sensitive, and where the engineering effort should be concentrated.</p>
<h2 id="heading-security-as-a-business-rule">Security as a Business Rule</h2>
<p>Domain-Driven Design teaches us that business logic makes or breaks an application. The domain layer is where the rules that define the system's correctness live. Security requirements are business rules, and they belong in the domain layer alongside every other business rule.</p>
<p>A sales agent shouldn't be able to create a sale without confirmed coverage. That's a business rule. It belongs in the domain entity or domain service that creates sales, enforced at the point of creation, impossible to bypass from any layer above.</p>
<p>A payment shouldn't transition from pending to completed without going through the processing state. That's a business rule. It belongs in the Payment entity's state machine, enforced at the entity level, impossible to corrupt through the API or the infrastructure layer.</p>
<p>An account transfer shouldn't proceed if the source account is flagged for fraud review. That's both a business rule and a security requirement. It belongs in the domain service that orchestrates transfers, enforced before any money moves.</p>
<p>When security requirements are encoded as domain business rules, they can't be bypassed by calling the API directly, by using a different client, or by accessing the database through an ORM. The rule is enforced at the point where the domain object is created or its state is changed. Every path through the system hits the domain layer. The domain layer enforces the rule.</p>
<p>Value Objects strengthen this further. A Money value object that validates on construction means no invalid amount can ever exist in the domain. An AccountNumber value object that validates format and check digits means no malformed account number can enter the system. The validation isn't a controller check that can be skipped. It's an intrinsic property of the type itself.</p>
<p>This is the engineering mechanism for Secure by Design at the domain level: encode security requirements as constraints on domain types and domain operations, and make them impossible to bypass.</p>
<h2 id="heading-encryption-standards-the-organizational-decision">Encryption Standards: The Organizational Decision</h2>
<p>One of the most dangerous security decisions in most organizations is the one that's not made: what encryption standard does the organization use?</p>
<p>When there is no organizational standard, every developer makes their own choice. One team uses AES-128. Another uses AES-256 with CBC mode. A third uses AES-256 with GCM mode. A fourth is still using MD5 for something.</p>
<p>Nobody intended for this to happen. It happened because nobody made the decision at the organizational level and enforced it.</p>
<p>The vulnerabilities that come from ad-hoc encryption choices are serious and often subtle. Padding oracle attacks exploit specific combinations of cipher mode and error handling. CBC mode with improper IV generation is vulnerable to attacks that GCM mode is not. Weak key lengths can be brute-forced. Exposing stack traces during encryption failures reveals internal implementation details that help attackers.</p>
<p>Every organization that handles sensitive data must make these decisions explicitly and enforce them as engineering standards:</p>
<h3 id="heading-1-which-symmetric-encryption-algorithm-and-mode">1. Which Symmetric Encryption Algorithm and Mode?</h3>
<p>Symmetric encryption uses the same key to encrypt and decrypt data. It is fast and efficient, making it the right choice for encrypting large amounts of data at rest or in transit.</p>
<p><strong>AES-256 with GCM mode</strong> is the current standard for most applications. AES stands for Advanced Encryption Standard. The 256 refers to the key size in bits: usually a longer key means more possible combinations and a harder brute force attack.</p>
<p>GCM (Galois/Counter Mode) provides authenticated encryption, meaning it both encrypts the data and produces an authentication tag that detects whether the ciphertext has been tampered with. You get confidentiality and integrity in one operation.</p>
<p>CBC (Cipher Block Chaining) mode is still used but requires careful handling of initialization vectors (IVs) and message authentication codes (MACs) to achieve the same properties GCM provides natively. Getting this wrong opens the door to padding oracle attacks, where an attacker can decrypt data or forge ciphertext by carefully observing how the system responds to modified ciphertext.</p>
<h3 id="heading-2-which-hashing-algorithm-for-passwords">2. Which Hashing Algorithm for Passwords?</h3>
<p>Hashing is a one-way operation. You can't reverse a hash back into the original value. This is why you store a hash of a password, not the password itself. When a user logs in, you hash what they typed and compare it to the stored hash.</p>
<p><strong>bcrypt, scrypt, and Argon2</strong> are the current standards for password hashing. These algorithms are deliberately slow and computationally expensive, which makes brute force attacks impractical even when an attacker obtains the hash database.</p>
<p><strong>SHA-256 isn't a password hashing algorithm.</strong> It's a general-purpose cryptographic hash function that is fast by design...and this is exactly what you don't want for passwords. An attacker can try billions of SHA-256 hashes per second on modern hardware.</p>
<p><strong>MD5 isn't a hashing algorithm for anything sensitive.</strong> It was broken years ago and should never appear in any security-sensitive context. These aren't just my opinions. They're the product of cryptographic research and real-world attacks.</p>
<h3 id="heading-3-which-asymmetric-algorithms-for-signing-and-key-exchange">3. Which Asymmetric Algorithms for Signing and Key Exchange?</h3>
<p>Asymmetric encryption uses a pair of keys: a public key that anyone can see and a private key that only you hold. Data encrypted with the public key can only be decrypted with the private key. A signature created with the private key can be verified by anyone with the public key.</p>
<p>Use <strong>RSA-2048 at a minimum</strong> for asymmetric operations. Use <strong>RS256 or ES256</strong> for JWT signing in high-security contexts. RS256 uses RSA with SHA-256 for signing. ES256 uses Elliptic Curve Digital Signature Algorithm (ECDSA) with the P-256 curve. EC keys are generally preferred over RSA at equivalent security levels because they produce smaller keys and signatures while providing the same cryptographic strength.</p>
<h3 id="heading-4-how-encryption-is-delivered-to-developers">4. How Encryption is Delivered to Developers</h3>
<p>The most important decision is that you don't implement encryption from scratch per project. Staff engineers build encryption utilities as internal packages or cloud functions. Then you can import and use them. You should never write the cryptographic primitives yourself. This eliminates an entire category of implementation failures at the source.</p>
<p>When encryption implementation is centralized, fixing a vulnerability means fixing it in one place. When it's scattered across every project, fixing a vulnerability means finding every implementation first, which is often impossible.</p>
<h2 id="heading-database-security">Database Security</h2>
<p>The database is where the most sensitive data in most systems lives. It's also one of the most frequently misconfigured components in the entire stack.</p>
<h3 id="heading-sql-injection">SQL Injection</h3>
<p>SQL injection is 25 years old. It has existed since 1998. It still appears in production systems because engineering standards aren't enforced.</p>
<p>The cause is always the same: string concatenation. A developer takes user input and glues it directly into a SQL string. The database can't distinguish between the query the developer intended and the query the attacker constructed.</p>
<pre><code class="language-sql">-- developer intended this
SELECT * FROM users WHERE email = 'user@example.com'

-- attacker passes: anything@example.com' OR '1'='1
SELECT * FROM users WHERE email = 'anything@example.com' OR '1'='1'
-- returns every user in the table
</code></pre>
<p>The fix is parameterized queries or ORMs, always. The query structure is fixed. The values are passed separately. The database treats them as data, not as part of the query structure.</p>
<p>Static analysis in the CI/CD pipeline must flag raw SQL string concatenation. This is a zero-tolerance policy. Raw SQL strings with user input concatenated are never acceptable and must not reach production.</p>
<h3 id="heading-principle-of-least-privilege-for-database-access">Principle of Least Privilege for Database Access</h3>
<p>The application's database user should have exactly the permissions it needs and nothing more. A read-only reporting endpoint should connect as a user with SELECT permissions only. It shouldn't have INSERT, UPDATE, or DELETE. An API that only writes shouldn't have DROP TABLE permissions.</p>
<p>This limits the blast radius of a successful SQL injection or credential leak. If the application can only SELECT from specific tables, an attacker who compromises the database credentials can only SELECT from those tables. They can't DROP the database, INSERT false records, or UPDATE account balances.</p>
<p>This is a database provisioning decision that must be made explicitly for each application component and enforced at the infrastructure level.</p>
<h3 id="heading-all-database-connections-must-be-encrypted">All Database Connections Must Be Encrypted</h3>
<p>Database connections must use TLS. An unencrypted database connection transmits query results in plaintext on the network. Any component between the application and the database that can observe network traffic can read every query result.</p>
<p>In cloud environments, services often communicate over internal networks that feel secure but are not. Encrypting database connections isn't optional.</p>
<p>Here's what enforcing TLS on a database connection looks like in practice:</p>
<pre><code class="language-dart">final connection = await Connection.open(
  Endpoint(
    host: 'your-db-host.example.com',
    port: 5432,
    database: 'your_database',
    username: dbUser,
    password: dbPassword,
  ),
  settings: ConnectionSettings(
    sslMode: SslMode.require,
  ),
);
</code></pre>
<pre><code class="language-csharp">var connectionString =
    "Host=your-db-host.example.com;" +
    "Port=5432;" +
    "Database=your_database;" +
    "Username=db_user;" +
    "Password=db_password;" +
    "SSL Mode=Require;" +
    "Trust Server Certificate=false;";

await using var dataSource = NpgsqlDataSource.Create(connectionString);
</code></pre>
<p>Setting <code>SSL Mode=Require</code> means the connection will fail entirely if the database server doesn't support TLS. This is the correct posture. A connection that silently falls back to plaintext when TLS is unavailable provides no protection at all.</p>
<h3 id="heading-database-credentials-must-live-in-vaults">Database Credentials Must Live in Vaults</h3>
<p>Database credentials must be fetched from a secrets manager at runtime. Not stored in configuration files, committed to version control, or hardcoded in connection strings.</p>
<p>Here's how runtime credential fetching works in practice:</p>
<pre><code class="language-dart">final dbHost = Platform.environment['DB_HOST']!;
final dbUser = Platform.environment['DB_USER']!;
final dbPassword = Platform.environment['DB_PASSWORD']!;

final connection = await Connection.open(
  Endpoint(
    host: dbHost,
    database: 'your_database',
    username: dbUser,
    password: dbPassword,
  ),
  settings: ConnectionSettings(sslMode: SslMode.require),
);
</code></pre>
<pre><code class="language-csharp">builder.Configuration.AddAzureKeyVault(
    new Uri("https://your-vault.vault.azure.net/"),
    new DefaultAzureCredential()
);

var connectionString = builder.Configuration["DatabaseConnectionString"];
</code></pre>
<p>Connection pooling must also be properly controlled. An unbounded connection pool can exhaust the database server's available connections, taking it down for all tenants. Configure pool size deliberately:</p>
<pre><code class="language-csharp">var dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString);
dataSourceBuilder.ConnectionStringBuilder.MaxPoolSize = 20;
dataSourceBuilder.ConnectionStringBuilder.MinPoolSize = 5;
dataSourceBuilder.ConnectionStringBuilder.ConnectionIdleLifetime = 300;
await using var dataSource = dataSourceBuilder.Build();
</code></pre>
<h3 id="heading-stored-procedures-as-a-parameterization-strategy">Stored Procedures as a Parameterization Strategy</h3>
<p>A stored procedure is a named, pre-compiled SQL block stored inside the database itself. Instead of sending a full SQL string from your application, you call the procedure by name and pass parameters separately.</p>
<p>Because the SQL structure is fixed inside the database and the parameters are always treated as data (never concatenated into the query string), stored procedures are resistant to SQL injection.</p>
<pre><code class="language-sql">CREATE OR REPLACE PROCEDURE get_user_by_email(p_email VARCHAR(255))
LANGUAGE plpgsql
AS $$
BEGIN
    SELECT id, first_name, last_name, email
    FROM users
    WHERE email = p_email;
END;
$$;
</code></pre>
<pre><code class="language-csharp">public async Task&lt;User?&gt; FindUserByEmail(string email)
{
    await using var command = dataSource.CreateCommand("get_user_by_email");
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.AddWithValue("p_email", email);

    await using var reader = await command.ExecuteReaderAsync();
    if (await reader.ReadAsync())
    {
        return new User
        {
            Id = reader.GetGuid(0),
            FirstName = reader.GetString(1),
            LastName = reader.GetString(2),
            Email = reader.GetString(3)
        };
    }
    return null;
}
</code></pre>
<p>An attacker who passes <code>' OR '1'='1</code> as the email value gets exactly that string as the parameter. The database never interprets it as SQL syntax. The procedure only executes the fixed query defined at creation time. This is one of the reasons stored procedures remain a legitimate security tool, not just a performance optimization.</p>
<h2 id="heading-cors-the-boundary-your-api-enforces">CORS: The Boundary Your API Enforces</h2>
<p>Cross-Origin Resource Sharing is the browser security mechanism that controls which domains can make requests to your API from web pages.</p>
<p>The most common CORS misconfiguration in production is also the most dangerous: wildcard CORS.</p>
<pre><code class="language-plaintext">Access-Control-Allow-Origin: *
</code></pre>
<p>This tells every browser that any web page on the entire internet can make authenticated requests to your API using that user's credentials. An attacker hosts a malicious web page, a user visits it, and the attacker's page can make requests to your API as that user.</p>
<p>In development, wildcard CORS is convenient. In production, it's a vulnerability.</p>
<p>Every production API must configure CORS with explicit allowed origins. Not wildcard patterns. Not <code>*.yourapp.com</code>. Explicit, enumerated domains that are allowed to make cross-origin requests.</p>
<pre><code class="language-plaintext">Access-Control-Allow-Origin: https://app.yourproduct.com
Access-Control-Allow-Origin: https://admin.yourproduct.com
</code></pre>
<p>Domain matching must be exact. If the origin header doesn't match one of the explicitly allowed origins, the browser won't include the response.</p>
<p>The allowed methods and allowed headers must also be explicit. The default deny posture applies: if it's not explicitly allowed, it's not allowed.</p>
<p>This is a configuration decision made at the API gateway or the framework level. It applies uniformly to all API endpoints, not endpoint by endpoint where individual developers might misconfigure it.</p>
<h2 id="heading-structured-logging-and-field-level-masking">Structured Logging and Field-Level Masking</h2>
<p>Logging is one of the most overlooked security surfaces in most systems. Developers add log statements to help debug. Those log statements travel to a logging platform. That logging platform retains logs for months or years. Those logs contain whatever the developer thought was useful to log when they were debugging at 11pm during an incident.</p>
<p>The result is that production logs often contain information that shouldn't be shared. For example, full request and response bodies, authorization headers with bearer tokens, user IDs paired with sensitive operations, account numbers, and sometimes passwords in plaintext because someone logged the raw request body before validation ran.</p>
<p>Again, this isn't hypothetical. These are real patterns found in real production logging platforms.</p>
<p>The engineering control is field-level masking applied at the logging framework level. Sensitive fields are defined once in the logging configuration. The framework masks those fields automatically in every log statement, in every environment, regardless of what the developer puts in the log statement.</p>
<p>Sensitive fields that must never appear in logs include: passwords, tokens and authorization headers, full account numbers and card numbers, BVN and NIN, any national identifier, encryption keys and secrets, and full request bodies for endpoints that handle sensitive data.</p>
<p>The masking must be framework-level, not developer-level. If you add a log statement, you shouldn't have to remember to mask sensitive fields. The framework handles it. You'll just log whatever is useful for debugging. The framework produces a log entry where sensitive fields are replaced with masked values.</p>
<p>Here's what field-level masking looks like in practice:</p>
<pre><code class="language-dart">class SecureLogger {
  final Logger _logger;

  static const _sensitiveKeys = {
    'password', 'authorization', 'token',
    'account_number', 'card_number', 'bvn', 'nin', 'secret', 'api_key',
  };

  SecureLogger(this._logger);

  void info(String message, {Map&lt;String, dynamic&gt;? data}) {
    _logger.info(message, _mask(data));
  }

  void error(String message, {Map&lt;String, dynamic&gt;? data, Object? error}) {
    _logger.error(message, _mask(data), error);
  }

  Map&lt;String, dynamic&gt;? _mask(Map&lt;String, dynamic&gt;? data) {
    if (data == null) return null;
    return data.map((key, value) {
      if (_sensitiveKeys.contains(key.toLowerCase())) {
        return MapEntry(key, '***MASKED***');
      }
      if (value is Map&lt;String, dynamic&gt;) return MapEntry(key, _mask(value));
      return MapEntry(key, value);
    });
  }
}

final logger = SecureLogger(Logger('PaymentService'));

logger.info('Processing payment', data: {
  'transaction_id': 'txn_001',
  'amount': 50000,
  'account_number': '0123456789',
  'authorization': 'Bearer eyJ...',
});

// output:
// Processing payment
// { transaction_id: txn_001, amount: 50000,
//   account_number: ***MASKED***, authorization: ***MASKED*** }
</code></pre>
<pre><code class="language-csharp">public class MaskSensitiveFieldsPolicy : IDestructuringPolicy
{
    private static readonly HashSet&lt;string&gt; SensitiveFields =
        new(StringComparer.OrdinalIgnoreCase)
        {
            "password", "authorization", "token", "account_number",
            "card_number", "bvn", "nin", "secret", "api_key"
        };

    public bool TryDestructure(
        object value,
        ILogEventPropertyValueFactory factory,
        out LogEventPropertyValue result)
    {
        if (value is not IDictionary&lt;string, object&gt; dict)
        {
            result = null!;
            return false;
        }

        var properties = dict.Select(kvp =&gt; new LogEventProperty(
            kvp.Key,
            SensitiveFields.Contains(kvp.Key)
                ? factory.CreatePropertyValue("***MASKED***")
                : factory.CreatePropertyValue(kvp.Value, true)));

        result = new StructureValue(properties);
        return true;
    }
}

Log.Logger = new LoggerConfiguration()
    .Destructure.With&lt;MaskSensitiveFieldsPolicy&gt;()
    .WriteTo.Console()
    .CreateLogger();
</code></pre>
<p>This applies in every environment without exception, not just production. Development logs are frequently exported to third-party logging platforms, and they're often searched by multiple team members. A developer who tests against a real account in development and logs the request body has put real user data into the logging platform where it doesn't belong.</p>
<h2 id="heading-cicd-security-gates">CI/CD Security Gates</h2>
<p>The CI/CD pipeline is the last automated gate before code reaches production. It's also one of the most consistently underused security controls in most engineering organizations.</p>
<p>Most pipelines run tests and check formatting. Security gates are the additional checks that catch the security-relevant issues that human code review consistently misses.</p>
<h3 id="heading-secret-detection">Secret Detection</h3>
<p>Every push to every branch must be scanned for secrets. API keys, database passwords, private keys, connection strings with credentials embedded, and JWT secrets in configuration files.</p>
<p><strong>Gitleaks</strong> is a free, open-source tool purpose-built for this. Here's how you integrate it into a GitHub Actions pipeline:</p>
<pre><code class="language-yaml"># .github/workflows/security.yml
name: Security Gates

on:
  push:
    branches: ["*"]
  pull_request:
    branches: ["*"]

jobs:
  secret-detection:
    name: Scan for secrets
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - uses: gitleaks/gitleaks-action@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
</code></pre>
<p>When Gitleaks finds a secret, it fails the pipeline, outputs the exact file and line number, and blocks the merge. You'll need to remove the secret, rotate the credential (because it touched version control and must be considered compromised), and push a clean commit before the pipeline passes.</p>
<p>The scan must run on the full Git history, not just the latest commit. A secret added three commits ago and removed in the next is still in the repository history and should be treated as compromised.</p>
<p>Your organization should also have a defined response procedure: who's notified when a secret is detected, which credentials are rotated, and in what timeframe. Detection without response isn't a security control.</p>
<h3 id="heading-static-analysis-for-security">Static Analysis for Security</h3>
<p>Static analysis tools analyze code for vulnerability patterns without running it. They catch raw SQL string concatenation, unsafe deserialization, hardcoded credentials, deprecated cryptographic functions, missing input validation, and dangerous function calls.</p>
<p><strong>Semgrep</strong> is a free, open-source static analysis tool with a large library of security rules maintained by the security community. Here's how it fits into a pipeline:</p>
<pre><code class="language-yaml">  static-analysis:
    name: Static analysis
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - uses: semgrep/semgrep-action@v1
        with:
          config: &gt;-
            p/owasp-top-ten
            p/secrets
            p/sql-injection
        env:
          SEMGREP_APP_TOKEN: ${{ secrets.SEMGREP_APP_TOKEN }}
</code></pre>
<p>The <code>p/owasp-top-ten</code> ruleset catches patterns corresponding to OWASP Top 10 vulnerabilities. The <code>p/sql-injection</code> ruleset specifically flags string concatenation in database queries. When Semgrep finds a match, the pipeline fails and identifies the exact file, line, and rule that triggered. The code can't merge until the issue is resolved.</p>
<p>For .NET projects, <strong>Microsoft Security Code Analysis</strong> and <strong>Roslyn Analyzers</strong> provide similar capabilities integrated directly into the build process.</p>
<p>The rules must be configured deliberately. Not every warning represents an actual vulnerability. Your team will define which rules are blocking, which are advisory, and which are suppressed. This configuration is itself a security decision that must be reviewed periodically.</p>
<h3 id="heading-dependency-vulnerability-scanning">Dependency Vulnerability Scanning</h3>
<p>Every dependency in the project is a potential attack surface. <strong>OWASP Dependency-Check</strong> is a free tool that scans project dependencies against the National Vulnerability Database (NVD) and flags known CVEs.</p>
<pre><code class="language-yaml">  dependency-scan:
    name: Dependency vulnerability scan
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - uses: dependency-check/Dependency-Check_Action@main
        with:
          project: "your-project-name"
          path: "."
          format: "HTML"
          args: &gt;
            --failOnCVSS 7
            --enableRetired

      - uses: actions/upload-artifact@v3
        if: always()
        with:
          name: dependency-check-report
          path: reports/
</code></pre>
<p>The <code>--failOnCVSS 7</code> flag means the pipeline fails if any dependency has a known vulnerability with a CVSS score of 7 or higher. CVSS (Common Vulnerability Scoring System) scores range from 0 to 10. A score of 7 or above is considered high severity. You can adjust this threshold based on your risk tolerance.</p>
<p>For Node.js projects, <code>npm audit</code> provides similar functionality out of the box. For Dart projects, <code>dart pub deps</code> combined with a vulnerability database check covers the dependency surface.</p>
<h3 id="heading-environment-specific-configuration-validation">Environment-Specific Configuration Validation</h3>
<p>Before deploying to production, the pipeline must validate that the production configuration meets the required security standards. This isn't just checking that configuration files exist. It's actively asserting that specific security-critical settings are correct.</p>
<p>Here's what that validation looks like as a pipeline step:</p>
<pre><code class="language-yaml">  config-validation:
    name: Validate production configuration
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v3

      - name: Validate security configuration
        run: |
          if grep -r "debugEndpoint\|swagger-ui\|/debug" src/ --include="*.dart" --include="*.cs"; then
            echo "ERROR: Debug endpoints found in production build"
            exit 1
          fi

          if grep -r "AllowAnyOrigin\|\*" config/ --include="*.yaml" --include="*.json"; then
            echo "ERROR: Wildcard CORS configuration detected"
            exit 1
          fi

          if grep -rE "(password|secret|key)\s*=\s*['\"][^$\{]" config/ --include="*.yaml" --include="*.json"; then
            echo "ERROR: Hardcoded credentials detected in configuration"
            exit 1
          fi

          if grep -r "showStackTrace.*true\|expose_errors.*true" config/ --include="*.yaml"; then
            echo "ERROR: Stack trace exposure enabled in production config"
            exit 1
          fi
</code></pre>
<p>This script runs before every production deployment. Debug endpoints, wildcard CORS, hardcoded credentials, and stack trace exposure are all blocking failures. The deployment can't proceed until every check passes.</p>
<h3 id="heading-different-workflows-for-different-environments">Different Workflows for Different Environments</h3>
<p>Development, staging, and production must have different pipeline workflows. Not just different deployment targets, but different validation requirements. The production pipeline is stricter than the staging pipeline. The staging pipeline is stricter than the development pipeline.</p>
<p>The production pipeline includes the full set of security gates. The development pipeline might skip some of the longer-running gates to preserve developer velocity. But the production pipeline never skips them.</p>
<p>This layered approach means that code progressively passes through stricter security validation as it approaches production. By the time it reaches the production deployment gate, it has already passed through multiple layers of automated security validation in lower environments.</p>
<h2 id="heading-microservices-and-internal-service-security">Microservices and Internal Service Security</h2>
<p>Building microservices introduces a security challenge that monolithic architectures don't have: every service-to-service communication is a potential attack surface.</p>
<p>In a monolith, a method call between components is a function call in memory. It can't be intercepted, forged, or tampered with in transit.</p>
<p>In a microservices architecture, every service call is a network request. Network requests can be intercepted, forged, and tampered with. Services that implicitly trust each other because they're "internal" are making a dangerous assumption.</p>
<p>Every microservice must treat incoming requests as untrusted by default, including requests from other internal services. Authentication is required for every service-to-service communication. The API gateway handles external authentication. Internal service-to-service authentication must be handled separately.</p>
<p>Two patterns cover the main scenarios: mTLS for synchronous calls and authenticated event streams for asynchronous communication.</p>
<p><strong>mTLS for synchronous service-to-service calls</strong> (mutual TLS) means both services present certificates to each other. The Payment Service calling the Account Service must present a valid certificate that the Account Service trusts. If the certificate is missing or invalid, the connection is rejected before any application code runs. This is cryptographic proof of identity: no bearer token to steal, no API key to rotate.</p>
<pre><code class="language-plaintext">Payment Service                    Account Service
      |                                  |
      |-- presents its certificate ----&gt; |
      |                                  |-- verifies certificate against trusted CA
      |                                  |-- rejects connection if invalid
      | &lt;-- presents its certificate --- |
      |-- verifies certificate           |
      |                                  |
      |-- authorized request ----------&gt; |
      |                                  |-- processes because identity is proven
</code></pre>
<p><strong>Authenticated event streams for asynchronous communication</strong> mean every message published to a broker carries a signature that consuming services verify before processing. A service that publishes a <code>PaymentCompleted</code> event signs it with its private key. The consuming service verifies the signature before acting on the event. A forged event without a valid signature is discarded.</p>
<pre><code class="language-dart">class PaymentEventPublisher {
  final KafkaProducer _producer;
  final EventSigner _signer;

  Future&lt;void&gt; publishPaymentCompleted(Payment payment) async {
    final event = PaymentCompletedEvent(
      paymentId: payment.id,
      amount: payment.amount,
      timestamp: DateTime.now().toIso8601String(),
    );

    final signature = await _signer.sign(jsonEncode(event.toJson()));

    await _producer.send(
      topic: 'payment.completed',
      value: jsonEncode({
        'payload': event.toJson(),
        'signature': signature,
        'publisher': 'payment-service',
      }),
    );
  }
}

class AccountEventConsumer {
  final EventVerifier _verifier;
  final AccountService _accountService;

  Future&lt;void&gt; onMessage(KafkaMessage message) async {
    final data = jsonDecode(message.value);
    final isValid = await _verifier.verify(
      jsonEncode(data['payload']),
      data['signature'] as String,
      data['publisher'] as String,
    );

    if (!isValid) {
      logger.warning('Invalid signature from ${data['publisher']} — discarding');
      return;
    }

    final event = PaymentCompletedEvent.fromJson(data['payload']);
    await _accountService.handlePaymentCompleted(event);
  }
}
</code></pre>
<p>Services must not be directly accessible from the internet without going through the API gateway. The gateway is the single entry point. It handles rate limiting, authentication, and routing for all external traffic. Services behind the gateway are internal: they're still not trusted by each other, but they're not exposed externally.</p>
<p>Overengineering is itself a security risk. An application that should be a well-designed monolith but is implemented as microservices introduces operational complexity that the team doesn't have the capacity to manage. Multiple deployment pipelines, multiple service boundaries, an API gateway, message brokers, and distributed tracing all require dedicated engineering capacity to operate securely. A monolith that isn't resourced to maintain properly is far less dangerous than a microservices architecture that isn't resourced to operate at all.</p>
<p>Choose your architecture based on what your team can actually operate securely, not based on what's fashionable.</p>
<h2 id="heading-data-privacy-and-compliance-as-engineering-requirements">Data Privacy and Compliance as Engineering Requirements</h2>
<p>Data privacy requirements are engineering requirements. They're not legal requirements that engineering accommodates. They're engineering requirements that engineering owns.</p>
<p>Under Nigeria's NDPA 2023, personal data must be processed only for specified, explicit, and legitimate purposes. BVN data has specific residency and handling requirements enforced by CBN guidelines. Under PCI-DSS, any environment that stores, processes, or transmits cardholder data is in scope for compliance.</p>
<p>These requirements have concrete engineering implications.</p>
<h3 id="heading-1-data-minimization">1. Data Minimization</h3>
<p>You can collect and store only the personal data that is actually needed for the specified purpose. An API that collects more data than it needs is creating compliance risk. A response that returns more data than the caller needs is both a BOPLA vulnerability and a data minimization violation.</p>
<h3 id="heading-2-purpose-limitation">2. Purpose Limitation</h3>
<p>Data collected for one purpose must not be used for a different purpose without proper basis. The engineering implication is that data that flows within the system must be documented and enforced. Data from one service must not flow to another service that uses it for an unauthorized purpose.</p>
<h3 id="heading-3-data-residency">3. Data Residency</h3>
<p>Certain categories of data must be stored in specific geographic regions. This is an infrastructure requirement that must be designed into the system architecture, not patched in after deployment.</p>
<h3 id="heading-4-retention-and-deletion">4. Retention and Deletion</h3>
<p>Personal data must be deleted when the purpose for which it was collected is fulfilled, or when the retention period defined in the privacy notice expires. The engineering implication is that every category of personal data must have a defined retention policy and an automated deletion mechanism. Manual deletion policies that depend on someone remembering to delete data aren't compliant.</p>
<h3 id="heading-5-audit-logging">5. Audit Logging</h3>
<p>Every access to personal data must be logged with sufficient detail to demonstrate compliance. Who accessed what data, when, for what stated purpose. This audit log must be tamper-evident and retained for the required period.</p>
<p>Here's what all five of these policies look like implemented together in a single feature (a user profile endpoint):</p>
<pre><code class="language-dart">class UserProfileService {
  final UserRepository _repository;
  final AuditLogger _auditLogger;
  final DataResidencyValidator _residencyValidator;

  UserProfileService(this._repository, this._auditLogger, this._residencyValidator);

  Future&lt;UserProfileResponse&gt; getProfile(
    String requestingUserId,
    String targetUserId,
    String purpose,
  ) async {
    if (!_isValidPurpose(purpose)) {
      throw UnauthorizedException('Invalid or undeclared access purpose');
    }

    final user = await _repository.findById(targetUserId);
    if (user == null) throw NotFoundException('User not found');

    _residencyValidator.assertCompliant(user.dataRegion, requestingUserId);

    await _auditLogger.log(AuditEntry(
      action: 'READ_USER_PROFILE',
      actorId: requestingUserId,
      resourceId: targetUserId,
      purpose: purpose,
      timestamp: DateTime.now(),
      dataFieldsAccessed: ['first_name', 'last_name', 'email'],
    ));

    return UserProfileResponse(
      id: user.id,
      firstName: user.firstName,
      lastName: user.lastName,
      email: user.email,
    );
  }

  bool _isValidPurpose(String purpose) {
    const validPurposes = {
      'user_self_view',
      'customer_support_verified',
      'compliance_audit',
    };
    return validPurposes.contains(purpose);
  }
}

class DataRetentionService {
  final UserRepository _repository;
  final AuditLogger _auditLogger;

  Future&lt;void&gt; enforceRetentionPolicy() async {
    final cutoff = DateTime.now().subtract(const Duration(days: 2555));
    final expiredUsers = await _repository.findInactiveUsersBefore(cutoff);

    for (final user in expiredUsers) {
      await _auditLogger.log(AuditEntry(
        action: 'AUTOMATED_DATA_DELETION',
        resourceId: user.id,
        purpose: 'retention_policy_enforcement',
        timestamp: DateTime.now(),
      ));

      await _repository.anonymize(user.id);
    }
  }
}
</code></pre>
<p>This single service demonstrates all five compliance policies in working code. Purpose is declared on every access. Data residency is validated before returning data. The audit log captures every access with full context. The response returns only the fields needed. And a scheduled job enforces deletion automatically without anyone having to remember.</p>
<p>These requirements must be part of the requirements specification for every feature that handles personal data. Not addressed after the feature is built. Addressed in the design.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Security isn't a feature you add to software. It's a property you engineer into it from the beginning.</p>
<p>Threat modeling before architecture decisions means you understand what you're protecting and what you're protecting it against before you decide how to build it.</p>
<p>Security as a business rule means the domain layer enforces security requirements the same way it enforces any other business rule, impossible to bypass, impossible to forget.</p>
<p>Encryption standards as an organizational decision means no developer is choosing cryptographic primitives by preference or convenience.</p>
<p>Database security means the application can only do what it needs to do, and an attacker who compromises one component can't compromise everything.</p>
<p>CORS configuration means the browser security mechanism is actually enforcing the boundary, not bypassed by a wildcard.</p>
<p>Structured logging with field-level masking means sensitive data never ends up in a log file regardless of what developers log.</p>
<p>And CI/CD security gates mean automated validation catches what human review misses, on every push, before every deployment.</p>
<p>None of these are exotic or difficult concepts. They're engineering disciplines that require deliberate decisions and deliberate enforcement. The decision not to make them is itself a decision, and it has consequences that show up in incident reports.</p>
<p>The most expensive place to address a security vulnerability is after it has been exploited. The second most expensive place is after it has shipped to production. The least expensive place is in the design, before a single line of code exists.</p>
<p>That's what Secure by Design means in practice. Not perfect security or zero risk. Just deliberate, documented, enforceable decisions about how the system handles adversarial conditions, made before the system is built, so the engineering is sound from the start.</p>
<p>One of the things to look forward to as an technology enthusiast is the day when applications are built with security as an integral part of that development process. Not as an afterthought or something that needs to pass just for deployment to happen. This is why you need to understand, accept, and adopt Secure by Design as a standardized process, not only in the Application Security Field but also in core software engineering.</p>
<p>Happy Secured Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Engineering Anatomy of API Vulnerabilities: A Deep Dive into the OWASP API Security Top 10 ]]>
                </title>
                <description>
                    <![CDATA[ Most security articles read like threat reports. They describe vulnerabilities from the outside looking in: what an attacker does, what the impact is, and how many systems are affected globally. That' ]]>
                </description>
                <link>https://www.freecodecamp.org/news/engineering-anatomy-of-api-vulnerabilities-owasp-api-security-top-10/</link>
                <guid isPermaLink="false">6ac381f06fd156dcaf4d765b</guid>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ securityawareness ]]>
                    </category>
                
                    <category>
                        <![CDATA[ OWASP TOP 10 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #OWASP LLM Top 10 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ application sec ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ owasp ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Application Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwaseyi Fatunmole ]]>
                </dc:creator>
                <pubDate>Mon, 05 Oct 2026 10:54:40 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/58e0ba94-ccc6-4e4e-aa19-9480cb060d23.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Most security articles read like threat reports. They describe vulnerabilities from the outside looking in: what an attacker does, what the impact is, and how many systems are affected globally. That's useful context, but it doesn't help engineers build better systems.</p>
<p>This article is different. It looks at each OWASP API Security Top 10 vulnerability from the inside: what engineering decision allowed it to exist, which architectural principle was violated, and what the engineering standard should be to prevent it from ever shipping to production.</p>
<p>I've spent years building production applications at scale in regulated financial environments. The vulnerabilities in this list aren't theoretical. I've seen most of them in real systems. Some of them I caught before they reached production. Some of them were already live when I arrived. Every single one of them was preventable...and not by security tools, but by engineering discipline.</p>
<p>That's the lens this article uses.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#heading-what-is-the-owasp-api-security-top-10">What is the OWASP API Security Top 10?</a></p>
</li>
<li><p><a href="#heading-1-broken-object-level-authorization-bola">1. Broken Object Level Authorization (BOLA)</a></p>
</li>
<li><p><a href="#heading-2-broken-authentication">2. Broken Authentication</a></p>
</li>
<li><p><a href="#heading-3-broken-object-property-level-authorization-bopla">3. Broken Object Property Level Authorization (BOPLA)</a></p>
</li>
<li><p><a href="#heading-4-unrestricted-resource-consumption">4. Unrestricted Resource Consumption</a></p>
</li>
<li><p><a href="#heading-5-broken-function-level-authorization-bfla">5. Broken Function Level Authorization (BFLA)</a></p>
</li>
<li><p><a href="#heading-6-unrestricted-access-to-sensitive-business-flows">6. Unrestricted Access to Sensitive Business Flows</a></p>
</li>
<li><p><a href="#heading-7-security-misconfiguration">7. Security Misconfiguration</a></p>
</li>
<li><p><a href="#heading-8-improper-inventory-management">8. Improper Inventory Management</a></p>
</li>
<li><p><a href="#heading-9-unsafe-consumption-of-apis">9. Unsafe Consumption of APIs</a></p>
</li>
<li><p><a href="#heading-10-server-side-request-forgery-ssrf">10. Server-Side Request Forgery (SSRF)</a></p>
</li>
<li><p><a href="#heading-engineering-vulnerabilities-beyond-the-owasp-list">Engineering Vulnerabilities Beyond the OWASP List</a></p>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before reading this article, you should be comfortable with:</p>
<ul>
<li><p>Building APIs in any language or framework</p>
</li>
<li><p>Basic understanding of authentication: what tokens and sessions are</p>
</li>
<li><p>What a database query looks like at a high level</p>
</li>
<li><p>General software architecture concepts, like layers, services, and gateways</p>
</li>
</ul>
<p>You don't need a security background. This article explains every vulnerability from an engineering perspective, not a security analyst perspective.</p>
<h2 id="heading-what-is-the-owasp-api-security-top-10">What is the OWASP API Security Top 10?</h2>
<p>OWASP stands for Open Web Application Security Project. It's a non-profit foundation that produces freely available security guidance for engineers and organizations. The OWASP API Security Top 10 is a regularly updated list of the most critical API vulnerabilities found in production systems globally.</p>
<p>It's not a theoretical list. It's compiled from real security incidents, penetration test findings, and vulnerability reports from production systems across industries. Every item on this list has caused real data breaches, real financial losses, and real regulatory penalties in real organizations.</p>
<p>Understanding this list isn't optional for engineers building APIs. It's foundational knowledge.</p>
<h2 id="heading-1-broken-object-level-authorization-bola">1. Broken Object Level Authorization (BOLA)</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>A user is authenticated and they have a valid token. But they can access data that doesn't belong to them simply by changing an identifier in the request.</p>
<pre><code class="language-plaintext">GET /api/accounts/12345/transactions
</code></pre>
<p>User A is authenticated and owns account 12345. They change the account number:</p>
<pre><code class="language-plaintext">GET /api/accounts/99999/transactions
</code></pre>
<p>If the API returns User B's transactions, BOLA exists. The user is authenticated but the API isn't verifying that the authenticated user owns the requested resource.</p>
<p>This is the most common API vulnerability in the world. It consistently tops the OWASP list because it's so easy to introduce and so easy to miss in code review.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>BOLA happens when authorization is treated as a binary question: is this user authenticated? Yes or no. The API checks whether the user has a valid token and stops there. It never asks the second question: does this authenticated user own the specific resource they're requesting?</p>
<p>The authentication isn't ID-agnostic. It proves who you are but it never proves whether the thing you are asking for belongs to you.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Authorization must happen at the service layer, not just at the API gateway. The API gateway can verify that the token is valid. Only the service layer knows whether the authenticated user owns the resource being requested.</p>
<p><strong>Dart (service layer enforcement):</strong></p>
<pre><code class="language-dart">class TransactionService {
  final TransactionRepository _repository;
  final AuthContext _authContext;

  TransactionService(this._repository, this._authContext);

  Future&lt;Result&lt;List&lt;Transaction&gt;, AppException&gt;&gt; getTransactions(
    String accountId,
  ) async {
    final currentUserId = _authContext.currentUserId;

    // fetch the account first
    final account = await _repository.findAccountById(accountId);

    if (account == null) {
      return Result.failure(AppException.notFound('Account not found'));
    }

    // verify ownership before returning any data
    if (account.ownerId != currentUserId) {
      return Result.failure(
        AppException.forbidden('Access denied to this account'),
      );
    }

    final transactions = await _repository.findByAccountId(accountId);
    return Result.success(transactions);
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">public async Task&lt;Result&lt;IEnumerable&lt;Transaction&gt;&gt;&gt; GetTransactions(
    string accountId,
    ClaimsPrincipal currentUser)
{
    var userId = currentUser.FindFirst(ClaimTypes.NameIdentifier)?.Value;
    var account = await _repository.FindAccountByIdAsync(accountId);

    if (account == null)
        return Result.Failure&lt;IEnumerable&lt;Transaction&gt;&gt;("Account not found");

    // ownership check — never skip this
    if (account.OwnerId != userId)
        return Result.Failure&lt;IEnumerable&lt;Transaction&gt;&gt;("Access denied");

    var transactions = await _repository.FindByAccountIdAsync(accountId);
    return Result.Success(transactions);
}
</code></pre>
<p>The ownership check must happen on every request that accesses a specific resource. Not just on first load or on write operations. Every single request.</p>
<h2 id="heading-2-broken-authentication">2. Broken Authentication</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>Weak tokens, no token expiry, no rate limiting on authentication endpoints, or sessions that never terminate on logout. Any weakness in the mechanism that identifies who's making a request.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>Authentication is treated as a solved problem once it's working. Engineers implement login, get a token back, and move on. The failure modes (like what happens when a token is stolen, or if an attacker hammers the login endpoint with a list of passwords, or when a user logs out) are never designed for.</p>
<p>The authentication mechanism must be designed for adversarial conditions, not just for happy path usage.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p><strong>Token expiry is mandatory.</strong> Access tokens should be short-lived: 15 minutes to 1 hour. Refresh tokens handle session continuity. Short-lived access tokens limit the damage window when a token is stolen.</p>
<p><strong>Rate limiting on authentication endpoints is mandatory.</strong> A login endpoint without rate limiting is an open invitation for brute force attacks. An attacker with a list of 10 million email and password combinations will systematically try every one.</p>
<p><strong>Sessions must actually terminate on logout.</strong> If you're using stateful sessions, the session must be invalidated server-side on logout. If you're using JWT, maintain a token blocklist or use a very short expiry with refresh token rotation.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">class AuthService {
  final TokenRepository _tokenRepository;
  final RateLimiter _rateLimiter;

  AuthService(this._tokenRepository, this._rateLimiter);

  Future&lt;Result&lt;AuthTokens, AppException&gt;&gt; login(
    String email,
    String password,
    String ipAddress,
  ) async {
    // rate limit by IP to prevent brute force
    final isAllowed = await _rateLimiter.checkLimit(
      key: 'login:$ipAddress',
      maxAttempts: 5,
      windowSeconds: 300,
    );

    if (!isAllowed) {
      return Result.failure(
        AppException.rateLimited('Too many login attempts. Try again later.'),
      );
    }

    final user = await _validateCredentials(email, password);

    if (user == null) {
      return Result.failure(
        AppException.unauthorized('Invalid credentials'),
      );
    }

    // short-lived access token
    final accessToken = _generateAccessToken(user, expiryMinutes: 15);

    // longer-lived refresh token, stored server-side
    final refreshToken = _generateRefreshToken(user);
    await _tokenRepository.storeRefreshToken(user.id, refreshToken);

    return Result.success(AuthTokens(
      accessToken: accessToken,
      refreshToken: refreshToken,
    ));
  }

  Future&lt;void&gt; logout(String userId, String refreshToken) async {
    // invalidate the refresh token server-side on logout
    await _tokenRepository.revokeRefreshToken(userId, refreshToken);
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">public async Task&lt;Result&lt;AuthTokens&gt;&gt; Login(
    LoginRequest request,
    string ipAddress)
{
    var isAllowed = await _rateLimiter.CheckLimit(
        key: $"login:{ipAddress}",
        maxAttempts: 5,
        windowSeconds: 300);

    if (!isAllowed)
        return Result.Failure&lt;AuthTokens&gt;("Too many login attempts.");

    var user = await _userService.ValidateCredentials(
        request.Email,
        request.Password);

    if (user == null)
        return Result.Failure&lt;AuthTokens&gt;("Invalid credentials");

    var accessToken = _tokenService.GenerateAccessToken(user, expiryMinutes: 15);
    var refreshToken = _tokenService.GenerateRefreshToken(user);

    await _tokenRepository.StoreRefreshToken(user.Id, refreshToken);

    return Result.Success(new AuthTokens(accessToken, refreshToken));
}

public async Task Logout(string userId, string refreshToken)
{
    await _tokenRepository.RevokeRefreshToken(userId, refreshToken);
}
</code></pre>
<h2 id="heading-3-broken-object-property-level-authorization-bopla">3. Broken Object Property Level Authorization (BOPLA)</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>The API returns more data than the user needs. Internal flags, admin permissions, and sensitive fields that should never leave the server end up in the response payload. Or worse: the API accepts more data than the user should be able to set, allowing users to modify fields they should never touch.</p>
<p>A user fetches their profile and the response includes <code>isAdmin: false</code>, <code>internalAccountScore: 742</code>, or <code>fraudRiskLevel: "low"</code>. None of these should ever be in a user-facing response.</p>
<p>Or a user updates their profile and the request body includes <code>"role": "admin"</code>. The API processes it. The user has just promoted themselves to admin.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>This is a structure problem. It happens when systems are built without a deliberately designed response schema. Some developers return the raw database entity directly because it's easier. Some lack the domain knowledge to properly structure their data layer. The result is that internal data leaks into external responses.</p>
<p>This is also an Interface Segregation Principle violation. The response interface forces the consumer to receive data it should never have access to.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Every API endpoint must have an explicit, deliberately designed response DTO. The response DTO contains only the fields the caller is authorized to receive. The domain entity never travels directly to the response.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">//Wrong returning the domain entity directly - exposes internal fields
Future&lt;Response&gt; getProfile(Request request) async {
  final user = await _userRepository.findById(userId);
  return Response.ok(jsonEncode(user.toJson())); // exposes everything
}

// Correct : explicit response DTO — only what the caller should see
class UserProfileResponse {
  final String id;
  final String firstName;
  final String lastName;
  final String email;

  const UserProfileResponse({
    required this.id,
    required this.firstName,
    required this.lastName,
    required this.email,
  });

  Map&lt;String, dynamic&gt; toJson() =&gt; {
    'id': id,
    'first_name': firstName,
    'last_name': lastName,
    'email': email,
    // isAdmin, internalScore, fraudRiskLevel — never here
  };
}

Future&lt;Response&gt; getProfile(Request request) async {
  final user = await _userRepository.findById(userId);

  final response = UserProfileResponse(
    id: user.id,
    firstName: user.firstName,
    lastName: user.lastName,
    email: user.email,
  );

  return Response.ok(jsonEncode(response.toJson()));
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">// Wrong = returning the domain model directly
public async Task&lt;IActionResult&gt; GetProfile(string userId)
{
    var user = await _repository.FindByIdAsync(userId);
    return Ok(user); 
}

// Correct explicit response DTO
public record UserProfileResponse(
    string Id,
    string FirstName,
    string LastName,
    string Email);

public async Task&lt;IActionResult&gt; GetProfile(string userId)
{
    var user = await _repository.FindByIdAsync(userId);

    var response = new UserProfileResponse(
        user.Id,
        user.FirstName,
        user.LastName,
        user.Email
        // IsAdmin, InternalScore, FraudRiskLevel — never exposed
    );

    return Ok(response);
}
</code></pre>
<p>For incoming requests, use a request DTO that only accepts the fields a user is permitted to modify. Never bind directly to a domain entity in an update operation.</p>
<h2 id="heading-4-unrestricted-resource-consumption">4. Unrestricted Resource Consumption</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>No rate limiting. A caller can spam critical APIs thousands of times per minute, such as with scraping, brute forcing, or denial of service attacks. The API accepts every request without any throttling or limit on consumption.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>Rate limiting is treated as optional or as a future concern. It's deferred to "when we need to scale" or "when we see abuse." By the time abuse is visible, the damage is already happening. A financial API without rate limiting can be brute-forced for valid account numbers, scraped for pricing data, or simply overwhelmed into unavailability.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Rate limiting must be implemented at the API gateway layer, before requests reach the service layer. This isn't a service responsibility. The gateway is the right enforcement point because it can handle this for all services simultaneously without each service reimplementing it.</p>
<p>Different endpoints need different limits. Authentication endpoints need strict limits (5 attempts per 5 minutes per IP). Public read endpoints need moderate limits. Write operations on sensitive resources need strict limits.</p>
<p><strong>Dart (middleware approach):</strong></p>
<pre><code class="language-dart">class RateLimitMiddleware {
  final RateLimiter _limiter;

  RateLimitMiddleware(this._limiter);

  Handler call(Handler innerHandler) {
    return (Request request) async {
      final clientIp = request.headers['x-forwarded-for'] ?? 'unknown';
      final endpoint = request.url.path;

      final limit = _getLimitForEndpoint(endpoint);
      final isAllowed = await _limiter.checkLimit(
        key: '$clientIp:$endpoint',
        maxRequests: limit.maxRequests,
        windowSeconds: limit.windowSeconds,
      );

      if (!isAllowed) {
        return Response(
          429,
          body: jsonEncode({'error': 'Rate limit exceeded'}),
          headers: {'Retry-After': '60'},
        );
      }

      return innerHandler(request);
    };
  }

  RateLimit _getLimitForEndpoint(String path) {
    if (path.contains('/auth/login')) {
      return RateLimit(maxRequests: 5, windowSeconds: 300);
    }
    if (path.contains('/transactions')) {
      return RateLimit(maxRequests: 100, windowSeconds: 60);
    }
    return RateLimit(maxRequests: 1000, windowSeconds: 60);
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">// using AspNetCoreRateLimit
builder.Services.AddRateLimiter(options =&gt;
{
    options.AddFixedWindowLimiter("auth", limiterOptions =&gt;
    {
        limiterOptions.PermitLimit = 5;
        limiterOptions.Window = TimeSpan.FromMinutes(5);
        limiterOptions.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        limiterOptions.QueueLimit = 0;
    });

    options.AddFixedWindowLimiter("standard", limiterOptions =&gt;
    {
        limiterOptions.PermitLimit = 100;
        limiterOptions.Window = TimeSpan.FromMinutes(1);
    });

    options.RejectionStatusCode = 429;
});

// apply per controller
[EnableRateLimiting("auth")]
[HttpPost("login")]
public async Task&lt;IActionResult&gt; Login(LoginRequest request) { }

[EnableRateLimiting("standard")]
[HttpGet("transactions")]
public async Task&lt;IActionResult&gt; GetTransactions() { }
</code></pre>
<h2 id="heading-5-broken-function-level-authorization-bfla">5. Broken Function Level Authorization (BFLA)</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>A regular user gets access to functions or endpoints that should only be accessible to admins or privileged roles. The frontend hides the button, but the endpoint is still there, wide open.</p>
<p>A regular user token is used to call an admin endpoint. It works. The attacker now has admin functionality with a non-admin account.</p>
<p>Security through obscurity is not security. Hiding admin resources at the UI level doesn't equal security.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>RBAC (Role-Based Access Control) is either not implemented or implemented incorrectly. Authorization checks are missing at the function level. The assumption is that if a user can't see the admin button in the UI, they can't call the admin API. This assumption is always wrong. Any developer tool can call any API endpoint directly, bypassing the UI entirely.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Every function must check the caller's role before executing. This check must happen in the service layer, not the UI layer, and not the API gateway alone. The gateway can verify that a token is valid. Only the service layer knows what roles are required for each specific operation.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">class UserManagementService {
  final AuthContext _authContext;
  final UserRepository _repository;

  UserManagementService(this._authContext, this._repository);

  Future&lt;Result&lt;void, AppException&gt;&gt; deleteUser(String targetUserId) async {
    final currentUser = _authContext.currentUser;

    // role check - this must happen in the service layer
    if (!currentUser.hasRole(UserRole.admin)) {
      return Result.failure(
        AppException.forbidden('Admin role required for this operation'),
      );
    }

    await _repository.deleteUser(targetUserId);
    return Result.success(null);
  }

  Future&lt;Result&lt;List&lt;User&gt;, AppException&gt;&gt; getAllUsers() async {
    final currentUser = _authContext.currentUser;

    if (!currentUser.hasRole(UserRole.admin)) {
      return Result.failure(
        AppException.forbidden('Admin role required'),
      );
    }

    final users = await _repository.findAll();
    return Result.success(users);
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">[ApiController]
[Route("api/admin/users")]
[Authorize]
public class UserManagementController : ControllerBase
{
    private readonly IUserManagementService _service;

    [HttpDelete("{userId}")]
    [Authorize(Roles = "Admin")] 
    public async Task&lt;IActionResult&gt; DeleteUser(string userId)
    {
        await _service.DeleteUser(userId);
        return NoContent();
    }

    [HttpGet]
    [Authorize(Roles = "Admin")]
    public async Task&lt;IActionResult&gt; GetAllUsers()
    {
        var users = await _service.GetAllUsers();
        return Ok(users);
    }
}
</code></pre>
<p>Role checks at the attribute level in C# and explicit role validation in the service layer in Dart both achieve the same thing: the check happens in code, not in the UI, and not in the API consumer's behavior.</p>
<h2 id="heading-6-unrestricted-access-to-sensitive-business-flows">6. Unrestricted Access to Sensitive Business Flows</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>Core business logic that should have strict guardrails has none. Users can bypass business rules and trigger flows that should never be allowed in their situation.</p>
<p>A sales agent creates a sale for a customer in an area that doesn't have coverage. The endpoint that creates the sale never verified that coverage exists. A business rule was violated. In financial terms, this causes loss. In operational terms, this causes the kind of problems that take months to untangle.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>Business logic isn't identified and isn't enforced at the domain layer. Domain-Driven Design exists precisely for this reason: business logic breaks or makes your application. When the domain layer isn't properly designed, and business rules aren't explicitly encoded, users can bypass them.</p>
<p>The guardrails are missing because the engineers didn't know the guardrails were supposed to exist there. This is a domain knowledge problem as much as a technical problem.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Business rules belong in the domain layer. This is what Value Objects and domain entities enforce. A sale can't be created unless coverage is confirmed. That rule is encoded into the domain, not into the API endpoint or the UI.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">class Sale {
  final String agentId;
  final String customerId;
  final CoverageArea coverageArea;
  final SaleStatus status;

  Sale._({
    required this.agentId,
    required this.customerId,
    required this.coverageArea,
    required this.status,
  });

  // business rule enforced at domain creation - no coverage, no sale
  static Result&lt;Sale, DomainException&gt; create({
    required String agentId,
    required String customerId,
    required CoverageArea coverageArea,
  }) {
    if (!coverageArea.hasActiveCoverage) {
      return Result.failure(
        DomainException('Cannot create sale: customer area has no active coverage'),
      );
    }

    return Result.success(Sale._(
      agentId: agentId,
      customerId: customerId,
      coverageArea: coverageArea,
      status: SaleStatus.pending,
    ));
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">public class Sale
{
    private Sale(string agentId, string customerId, CoverageArea area)
    {
        AgentId = agentId;
        CustomerId = customerId;
        CoverageArea = area;
        Status = SaleStatus.Pending;
    }

    public string AgentId { get; }
    public string CustomerId { get; }
    public CoverageArea CoverageArea { get; }
    public SaleStatus Status { get; private set; }

    // factory enforces the business rule no coverage, no sale
    public static Result&lt;Sale&gt; Create(
        string agentId,
        string customerId,
        CoverageArea coverageArea)
    {
        if (!coverageArea.HasActiveCoverage)
            return Result.Failure&lt;Sale&gt;(
                "Cannot create sale: no active coverage in this area");

        return Result.Success(new Sale(agentId, customerId, coverageArea));
    }
}
</code></pre>
<p>The endpoint that creates a sale calls the domain factory. The domain factory enforces the business rule. The rule can't be bypassed through the API because the API can't create a Sale that bypasses the factory.</p>
<h2 id="heading-7-security-misconfiguration">7. Security Misconfiguration</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>A developer's personal debugging process shipped to production. Verbose error messages exposing stack traces. Debug endpoints left active. Permissive CORS allowing any origin. Sensitive data in logs. The developer's local configuration running in a production environment.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>These types of issues tend to happen when there's no separation between development, staging, and production configurations. There's no pipeline gate that catches misconfiguration before it reaches production. Each developer manages their own configuration, which means every developer's habits and debugging preferences can end up in production.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Set up different workflows for every environment. The production pipeline must include static analysis, configuration validation, and linting that catches debug endpoints, permissive CORS, verbose error logging, and exposed secrets before a merge is allowed.</p>
<p><strong>Dart (environment-aware error handling):</strong></p>
<pre><code class="language-dart">class ErrorHandler {
  final Environment _environment;

  ErrorHandler(this._environment);

  Response handleException(Object error, StackTrace stackTrace) {
 
    logger.error('Unhandled exception', error: error, stackTrace: stackTrace);

    if (_environment.isProduction) {
      
      return Response.internalServerError(
        body: jsonEncode({'error': 'An internal error occurred'}),
      );
    }

    
    return Response.internalServerError(
      body: jsonEncode({
        'error': error.toString(),
        'stackTrace': stackTrace.toString(),
      }),
    );
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">
app.UseExceptionHandler(errorApp =&gt;
{
    errorApp.Run(async context =&gt;
    {
        context.Response.StatusCode = 500;
        context.Response.ContentType = "application/json";

        var error = context.Features.Get&lt;IExceptionHandlerFeature&gt;();
        if (error != null)
        {
            // log internally with full details
            logger.LogError(error.Error, "Unhandled exception");
        }

        // return generic message to caller
        await context.Response.WriteAsync(
            JsonSerializer.Serialize(new { error = "An internal error occurred" })
        );
    });
});

// CORS - explicit allowed origins, never wildcard in production
builder.Services.AddCors(options =&gt;
{
    options.AddPolicy("ProductionPolicy", policy =&gt;
    {
        policy.WithOrigins(
            "https://app.yourproduct.com",
            "https://admin.yourproduct.com"
        )
        .AllowedMethods("GET", "POST", "PUT", "DELETE")
        .AllowedHeaders("Authorization", "Content-Type");
        
    });
});
</code></pre>
<p>CORS in production must use explicit allowed origins. Wildcard CORS in production is a direct security failure that allows any web page on the internet to make authenticated requests to your API using the visitor's credentials.</p>
<h2 id="heading-8-improper-inventory-management">8. Improper Inventory Management</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>Deprecated APIs, decommissioned endpoints, and outdated API versions still running on the server. Nobody knows they exist and nobody owns them. But attackers find them and exploit them because old endpoints are often less secured than current ones.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>API lifecycle management is nobody's formal responsibility. Endpoints get created and features change. The old endpoint version is forgotten rather than retired. Over time, the API surface area grows with dead endpoints that still respond to requests, often without the security controls applied to newer endpoints.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Someone must own the API inventory. This is a formal engineering responsibility, not an optional practice. Every API endpoint must be documented, versioned, and have a defined lifecycle: active, deprecated, or decommissioned.</p>
<p>Deprecated endpoints should return a response header indicating their deprecation date. Decommissioned endpoints must return 410 Gone, not continue to process requests.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">// deprecated endpoint wrapper
Handler deprecatedEndpoint({
  required Handler handler,
  required DateTime removalDate,
  required String replacementEndpoint,
}) {
  return (Request request) async {
    final response = await handler(request);

    // add deprecation headers so clients know to migrate
    return response.change(headers: {
      'Deprecation': 'true',
      'Sunset': HttpDate.format(removalDate),
      'Link': '&lt;$replacementEndpoint&gt;; rel="successor-version"',
      'Warning': '299 - "This endpoint is deprecated and will be removed on ${removalDate.toIso8601String()}"',
    });
  };
}

// decommissioned endpoint
Future&lt;Response&gt; decommissionedEndpoint(Request request) async {
  return Response(
    410,
    body: jsonEncode({
      'error': 'This endpoint has been permanently removed',
      'replacement': '/api/v2/accounts',
    }),
  );
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">// mark endpoints as deprecated using ApiVersion attributes
[ApiController]
[ApiVersion("1.0", Deprecated = true)]
[Route("api/v{version:apiVersion}/accounts")]
public class AccountsV1Controller : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetAccount(string id)
    {
        Response.Headers.Add("Deprecation", "true");
        Response.Headers.Add("Sunset", "Sat, 01 Jan 2027 00:00:00 GMT");
        Response.Headers.Add("Link", "&lt;/api/v2/accounts/{id}&gt;; rel=\"successor-version\"");

        // still process the request during deprecation period
        return Ok(_service.GetAccount(id));
    }
}

// gone - permanent removal
[ApiController]
[Route("api/v1/legacy/accounts")]
public class LegacyAccountsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAll()
    {
        return StatusCode(410, new { error = "This endpoint has been permanently removed", replacement = "/api/v2/accounts" });
    }
}
</code></pre>
<h2 id="heading-9-unsafe-consumption-of-apis">9. Unsafe Consumption of APIs</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>Your application integrates with third-party services and trusts their data without validation or guardrails. Whatever the external API returns, your application processes it directly.</p>
<p>A third-party payment callback returns a transaction status. Your application trusts it without verifying the signature or validating the data structure. An attacker sends a forged callback to your callback URL. Your application processes it as legitimate.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>External services are treated as trusted by default. There's no defined contract for what valid data from an external service looks like. There's no validation layer between the external service response and the application's processing logic.</p>
<p>Trust is assumed rather than verified.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Every integration with an external service must have a defined contract. The contract specifies what valid data looks like, what fields are required, and what the valid ranges and formats are. Every response from an external service is validated against this contract before any processing happens.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">class PaymentCallbackService {
  final String _webhookSecret;

  PaymentCallbackService(this._webhookSecret);

  Future&lt;Result&lt;PaymentStatus, AppException&gt;&gt; processCallback(
    Map&lt;String, dynamic&gt; payload,
    String signature,
    String rawBody,
  ) async {
    // step 1: verify the signature before processing anything
    final isValid = _verifySignature(rawBody, signature, _webhookSecret);
    if (!isValid) {
      logger.warning('Invalid webhook signature received');
      return Result.failure(
        AppException.unauthorized('Invalid webhook signature'),
      );
    }

    // step 2: validate the payload structure against our contract
    final validationResult = _validateCallbackPayload(payload);
    if (validationResult.isFailure) {
      logger.warning('Invalid callback payload: ${validationResult.error}');
      return Result.failure(validationResult.error!);
    }

    // step 3: only now do we trust and process the data
    final status = PaymentStatus.fromString(payload['status'] as String);
    return Result.success(status);
  }

  bool _verifySignature(String body, String signature, String secret) {
    final hmac = Hmac(sha256, utf8.encode(secret));
    final digest = hmac.convert(utf8.encode(body));
    final expectedSignature = 'sha256=${base64.encode(digest.bytes)}';
    return expectedSignature == signature;
  }

  Result&lt;void, AppException&gt; _validateCallbackPayload(
    Map&lt;String, dynamic&gt; payload,
  ) {
    if (!payload.containsKey('transaction_id')) {
      return Result.failure(
        AppException.validation('Missing required field: transaction_id'),
      );
    }
    if (!payload.containsKey('status')) {
      return Result.failure(
        AppException.validation('Missing required field: status'),
      );
    }
    final validStatuses = {'success', 'failed', 'pending'};
    if (!validStatuses.contains(payload['status'])) {
      return Result.failure(
        AppException.validation('Invalid status value: ${payload['status']}'),
      );
    }
    return Result.success(null);
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">public class PaymentCallbackService
{
    private readonly string _webhookSecret;
    private readonly ILogger&lt;PaymentCallbackService&gt; _logger;

    public async Task&lt;Result&lt;PaymentStatus&gt;&gt; ProcessCallback(
        string rawBody,
        string signature,
        PaymentCallbackDto payload)
    {
        // verify signature first
        if (!VerifySignature(rawBody, signature))
        {
            _logger.LogWarning("Invalid webhook signature received");
            return Result.Failure&lt;PaymentStatus&gt;("Invalid webhook signature");
        }

        // validate payload
        if (string.IsNullOrEmpty(payload.TransactionId))
            return Result.Failure&lt;PaymentStatus&gt;("Missing transaction_id");

        var validStatuses = new[] { "success", "failed", "pending" };
        if (!validStatuses.Contains(payload.Status))
            return Result.Failure&lt;PaymentStatus&gt;($"Invalid status: {payload.Status}");

        return Result.Success(Enum.Parse&lt;PaymentStatus&gt;(payload.Status, true));
    }

    private bool VerifySignature(string body, string signature)
    {
        using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(_webhookSecret));
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(body));
        var expectedSignature = $"sha256={Convert.ToBase64String(hash)}";
        return CryptographicOperations.FixedTimeEquals(
            Encoding.UTF8.GetBytes(expectedSignature),
            Encoding.UTF8.GetBytes(signature)
        );
    }
}
</code></pre>
<p>It must be a standard of engineering to create verified contracts with external services before integration begins. Never trust, always verify.</p>
<h2 id="heading-10-server-side-request-forgery-ssrf">10. Server-Side Request Forgery (SSRF)</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>An API accepts a URL as input and makes a server-side request to that URL. An attacker provides a URL that points to internal infrastructure: <code>http://169.254.169.254/latest/meta-data/</code> (AWS metadata service), <code>http://internal-database:5432</code>, or <code>http://admin-panel.internal</code>. The server makes the request from inside the network, bypassing external firewalls.</p>
<p>Most payment systems take callback URLs or redirect URLs in the request. If the API forwards requests to those URLs without validation, it will happily make requests to internal infrastructure on behalf of the attacker.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>This is a design flaw that must be caught at the architectural layer, not the code layer. Any API that accepts URLs as input and makes server-side requests to those URLs is a potential SSRF target. The design decision to accept arbitrary URLs must come with the design decision to strictly validate those URLs.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Any API that accepts a URL must validate it against a list of allowed domains before making any request. This is a design decision. The allowlist is part of the API's specification, not an afterthought.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">class WebhookService {
  // only these domains are allowed to receive callbacks
  static const _allowedDomains = {
    'api.yourpartner.com',
    'hooks.yourintegration.com',
    'callbacks.trustedservice.io',
  };

  Future&lt;Result&lt;void, AppException&gt;&gt; registerCallbackUrl(String url) async {
    // validate before storing or using
    final validationResult = _validateCallbackUrl(url);
    if (validationResult.isFailure) {
      return Result.failure(validationResult.error!);
    }

    await _webhookRepository.save(url);
    return Result.success(null);
  }

  Result&lt;void, AppException&gt; _validateCallbackUrl(String url) {
    final uri = Uri.tryParse(url);

    if (uri == null) {
      return Result.failure(AppException.validation('Invalid URL format'));
    }

    // must be HTTPS in production
    if (uri.scheme != 'https') {
      return Result.failure(
        AppException.validation('Callback URL must use HTTPS'),
      );
    }

    // must be in the allowlist
    if (!_allowedDomains.contains(uri.host)) {
      return Result.failure(
        AppException.validation(
          'Callback URL domain is not in the approved list',
        ),
      );
    }

    // block internal IP ranges explicitly
    if (_isInternalAddress(uri.host)) {
      return Result.failure(
        AppException.validation('Callback URL cannot point to internal addresses'),
      );
    }

    return Result.success(null);
  }

  bool _isInternalAddress(String host) {
    final privateRanges = [
      '127.', '10.', '172.16.', '172.17.', '172.18.',
      '192.168.', '169.254.', 'localhost', '0.0.0.0',
    ];
    return privateRanges.any((range) =&gt; host.startsWith(range));
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">public class WebhookService
{
    private static readonly HashSet&lt;string&gt; AllowedDomains = new()
    {
        "api.yourpartner.com",
        "hooks.yourintegration.com",
        "callbacks.trustedservice.io"
    };

    public async Task&lt;Result&lt;bool&gt;&gt; RegisterCallbackUrl(string url)
    {
        var validationResult = ValidateCallbackUrl(url);
        if (!validationResult.IsSuccess)
            return Result.Failure&lt;bool&gt;(validationResult.Error);

        await _repository.SaveCallbackUrl(url);
        return Result.Success(true);
    }

    private Result&lt;bool&gt; ValidateCallbackUrl(string url)
    {
        if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
            return Result.Failure&lt;bool&gt;("Invalid URL format");

        if (uri.Scheme != "https")
            return Result.Failure&lt;bool&gt;("Callback URL must use HTTPS");

        if (!AllowedDomains.Contains(uri.Host))
            return Result.Failure&lt;bool&gt;("Domain not in approved list");

        if (IsInternalAddress(uri.Host))
            return Result.Failure&lt;bool&gt;("Internal addresses are not permitted");

        return Result.Success(true);
    }

    private bool IsInternalAddress(string host)
    {
        var internalPrefixes = new[]
        {
            "127.", "10.", "172.16.", "192.168.",
            "169.254.", "localhost", "0.0.0.0"
        };
        return internalPrefixes.Any(p =&gt; host.StartsWith(p));
    }
}
</code></pre>
<h2 id="heading-engineering-vulnerabilities-beyond-the-owasp-list">Engineering Vulnerabilities Beyond the OWASP List</h2>
<p>The OWASP list covers the most critical and most common API vulnerabilities. But engineering experience surfaces additional patterns that can create serious security gaps.</p>
<h3 id="heading-apis-called-by-multiple-clients-without-domain-allowlisting">APIs Called by Multiple Clients Without Domain Allowlisting</h3>
<p>Some APIs called by multiple clients don't enforce which domains are allowed to call them. This makes it possible for people to share API keys and access resources from unauthorized origins.</p>
<p>In large-scale organizations, this is a major security gap that often goes unnoticed because the API technically works correctly from every client.</p>
<p>The fix: every API that accepts an API key must also validate the calling domain. API keys and allowed domains must be explicitly paired.</p>
<h3 id="heading-exposing-secrets-in-code-and-logs">Exposing Secrets in Code and Logs</h3>
<p>A developer leaves secret keys, public keys, and credentials in their code, in their repository, or on their machine. Adding files to <code>.gitignore</code> isn't enough. These datasets must be fetched from a trusted secrets manager at runtime, never stored in source code.</p>
<p>Organizations must use vaults, Azure App Configuration, AWS Secrets Manager, or equivalent systems. This must be an engineering standard, not a developer preference. The vault access pattern must be standardized so developers don't have to figure this out per project.</p>
<h3 id="heading-microservices-talking-to-each-other-without-a-gateway">Microservices Talking to Each Other Without a Gateway</h3>
<p>If you are building microservices, every communication between services must be treated as sensitive. There must be an API gateway that handles authentication for all services. Services must not trust each other implicitly. Every inter-service call must be authenticated.</p>
<p>Communication between microservices should use event brokers like Kafka for asynchronous flows, or mTLS for synchronous flows. No microservice should be directly accessible from the internet without going through the gateway.</p>
<h3 id="heading-encryption-without-organizational-standards">Encryption Without Organizational Standards</h3>
<p>Organizations must have standardized encryption algorithms. Not developer-chosen algorithms, not algorithm-of-the-week, and not whatever the developer found in a Stack Overflow answer. A staff-level engineering decision must specify which algorithm, which mode, and which key length is the organizational standard.</p>
<p>The vulnerabilities that come from ad-hoc encryption choices are serious: padding oracle attacks, weak key lengths, IV reuse, and stack traces during encryption failures that reveal internal implementation details to callers.</p>
<p>The engineering control: expose internally built packages or cloud functions for encryption that projects import rather than implement. Developers use the package. They never write encryption from scratch per project.</p>
<h3 id="heading-sql-injection">SQL Injection</h3>
<p>SQL injection is 25 years old. It's been in existence since 1998. But it still happens because engineering standards aren't enforced.</p>
<p>It happens because developers build queries with string concatenation, taking user input and gluing it into a SQL string. The fix is parameterized queries or prepared statements, always. Raw SQL strings with user input concatenated are never acceptable.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">//Wrong  string concatenation — SQL injection vulnerability
Future&lt;User?&gt; findUser(String email) async {
  final query = "SELECT * FROM users WHERE email = '$email'";
  // attacker passes: admin@example.com' OR '1'='1
  // query becomes: SELECT * FROM users WHERE email = 'admin@example.com' OR '1'='1'
  // returns all users
  return await database.rawQuery(query);
}

// parameterized query — injection proof
Future&lt;User?&gt; findUser(String email) async {
  final results = await database.query(
    'users',
    where: 'email = ?',    
    whereArgs: [email],     
  );
  return results.isNotEmpty ? User.fromMap(results.first) : null;
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">// Wrong string concatenation
public async Task&lt;User?&gt; FindUser(string email)
{
    var query = $"SELECT * FROM Users WHERE Email = '{email}'";
    return await _context.Users.FromSqlRaw(query).FirstOrDefaultAsync();
}

// Correct parameterized query using EF Core
public async Task&lt;User?&gt; FindUser(string email)
{
    return await _context.Users
        .Where(u =&gt; u.Email == email)
        .FirstOrDefaultAsync();
}

// Correct parameterized raw SQL when needed
public async Task&lt;User?&gt; FindUserRaw(string email)
{
    return await _context.Users
        .FromSqlRaw("SELECT * FROM Users WHERE Email = {0}", email)
        .FirstOrDefaultAsync();
}
</code></pre>
<p>This is a major vulnerability that comes from core engineering decisions that should be under strict governance and compliance principles. These principles help establish development standards on projects and in organizations.</p>
<p>This could also be enforced at CI CD level. If static analysis in the CI/CD pipeline doesn't catch raw SQL string concatenation, your team should add it. This is a vulnerability class that should never reach production.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Every vulnerability in this list has one thing in common: it was preventable. Not by security tools applied after the fact, but by engineering discipline applied during design and development.</p>
<ul>
<li><p>BOLA is prevented by ID-aware authorization in the service layer.</p>
</li>
<li><p>Broken authentication is prevented by proper token design and rate limiting.</p>
</li>
<li><p>BOPLA is prevented by explicit response DTOs.</p>
</li>
<li><p>Unrestricted resource consumption is prevented by rate limiting at the gateway.</p>
</li>
<li><p>BFLA is prevented by role checks in code, not in the UI.</p>
</li>
<li><p>Sensitive business flow exposure is prevented by domain-driven design and proper business rule enforcement.</p>
</li>
<li><p>Security misconfiguration is prevented by environment-specific pipelines with automated gates.</p>
</li>
<li><p>Improper inventory management is prevented by formal API lifecycle ownership.</p>
</li>
<li><p>Unsafe API consumption is prevented by contract-first external integrations.</p>
</li>
<li><p>SSRF is prevented by URL allowlisting as a design decision.</p>
</li>
</ul>
<p>The pattern is consistent. Security isn't something you add to an application. It's something you engineer into the architecture from the beginning. Every decision in this article is an engineering decision: where does this check belong in the architecture? Which layer is responsible for this validation? What does the domain enforce? What does the gateway enforce? What does the pipeline catch?</p>
<p>Security by design isn't a security team's responsibility. It's an engineering team's responsibility. And it starts with understanding exactly what these vulnerabilities are, where they come from, and what the engineering standard is to prevent them.</p>
<p>As software engineers, this kind of next level thinking ensures our code doesn't fail these security tests.</p>
<p>Happy Secured Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
