Amazon DynamoDB · Update

Catch an injection attempt

A "profile" endpoint whose posted fields become the attributes to change, attacked two ways: an update expression in a field name, and a field that tries to rewrite the item's key; then the same form used honestly.

Set up for this page

The scenarios build on the sample application: SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print); SampleContext.Application.cs (dbContext.Service, the application's ARX service); SampleModel.cs (the DynamoDB layout and the schema catalog); SampleContext.Direct.cs (dbContext.Direct); DynamoDirectHelper.cs (the checks behind dbContext.Direct).

dbContext.Direct is the samples' own checking code on the plain driver, not part of ARX: leave it out of your application.

Before scenario 1 the sample runs this, so the service and the rows the scenarios use are there:

Set up
var customer = new ArxEntity("customer");
customer["customer_id"] = "C-D221";
customer["name"] = "Coho Winery";
customer["tier"] = "standard";
await service.CreateAsync(customer);

1 An expression in a field name

"name = :v0, tier" tries to set the tier too: ARX1017.

Already in scope: service (ArxDynamoDbService)

C#
try
{
    await UpdateProfileAsync(service, new() { ["name = :v0, tier"] = "gold" });
}
catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.SuspectedInjection)
{
    Console.WriteLine(exception.Message);
}
Used above

Defined once in this sample.

private static Task<int> UpdateProfileAsync(ArxDynamoDbService service, Dictionary<string, object> posted)
{
    var change = new ArxEntity("customer") { RecordId = ArxRecordId.Of("customer_id", "C-D221") };

    foreach (var field in posted)
    {
        change[field.Key] = field.Value;
    }

    return service.UpdateAsync(change);
}

Check it in the database

PartiQL

A PartiQL statement: run it in NoSQL Workbench, or with aws dynamodb execute-statement --statement, after the code has run.

SELECT "tier" FROM "crm" WHERE "PK" = 'CUSTOMER#C-D221' AND "SK" = 'PROFILE'

Expect: 1 item, tier "standard".

2 Rewrite the key

A posted "PK" field: the table's key belongs to ARX, so it's refused.

Already in scope: service (ArxDynamoDbService)

C#
try
{
    await UpdateProfileAsync(service, new() { ["PK"] = "CUSTOMER#someone-else" });
}
catch (ArxException exception)
{
    Console.WriteLine(exception.Message);
}
Used above

Defined once in this sample.

private static Task<int> UpdateProfileAsync(ArxDynamoDbService service, Dictionary<string, object> posted)
{
    var change = new ArxEntity("customer") { RecordId = ArxRecordId.Of("customer_id", "C-D221") };

    foreach (var field in posted)
    {
        change[field.Key] = field.Value;
    }

    return service.UpdateAsync(change);
}

Check it in the database

PartiQL

A PartiQL statement: run it in NoSQL Workbench, or with aws dynamodb execute-statement --statement, after the code has run.

SELECT "PK" FROM "crm" WHERE "PK" = 'CUSTOMER#C-D221'

Expect: 1 item, still under CUSTOMER#C-D221.

3 The honest request

The same endpoint, used as meant.

Already in scope: service (ArxDynamoDbService)

C#
await UpdateProfileAsync(service, new() { ["name"] = "Coho Winery & Vineyard" });

Console.WriteLine("name changed");
Used above

Defined once in this sample.

private static Task<int> UpdateProfileAsync(ArxDynamoDbService service, Dictionary<string, object> posted)
{
    var change = new ArxEntity("customer") { RecordId = ArxRecordId.Of("customer_id", "C-D221") };

    foreach (var field in posted)
    {
        change[field.Key] = field.Value;
    }

    return service.UpdateAsync(change);
}

Check it in the database

PartiQL

A PartiQL statement: run it in NoSQL Workbench, or with aws dynamodb execute-statement --statement, after the code has run.

SELECT "name" FROM "crm" WHERE "PK" = 'CUSTOMER#C-D221' AND "SK" = 'PROFILE'

Expect: 1 item, name "Coho Winery & Vineyard".

Good to know

Names reach DynamoDB only as placeholders (#n0), so a name can't add clauses to the update expression: one with expression syntax is ARX1017 before anything is sent. The table's own key attributes (PK, SK) are ARX's to write, never the caller's.

See also

Run the complete sample

The code above comes from one program, built in a fresh project and run against the database. To run it yourself, here is every file and step.

The program, its files and how to run it

Run it locally

  1. .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target net10.0).
  2. Create the project:
    Terminal
    dotnet new console -n ArxSample -f net10.0
    cd ArxSample
  3. Install the packages:
    Terminal
    dotnet add package ARX.SDK.DynamoDb --version 1.0.0-rc.1
  4. Database: a Amazon DynamoDB, or DynamoDB Local for development (tested with DynamoDB Local 2.5.2) database with the sample schema.
  5. Configuration: set ARX_SAMPLES_DYNAMODB to its connection string. Nothing is hard-coded.
  6. Source code: add the files of the sample application this sample uses (SampleContext.cs, SampleOutput.cs, SampleContext.Application.cs, SampleModel.cs, SampleContext.Direct.cs, DynamoDirectHelper.cs), then replace Program.cs and add the other file below, with the file names shown.
  7. Run it:
    Terminal
    dotnet run
  8. Expected output: below.

The files

Program.cs

Runs the sample. Generated for this page; it reads the connection string from the environment and first remakes the sample database from sample-schema.json.

using ArxSamples.DynamoDb;
using ArxSamples.DynamoDb.Operations.Update.RealCases;

// The connection string comes from the environment, never from the code (see "Configure the connection").
var connectionString = Environment.GetEnvironmentVariable("ARX_SAMPLES_DYNAMODB")
    ?? throw new InvalidOperationException("Set the ARX_SAMPLES_DYNAMODB environment variable to your Amazon DynamoDB connection string.");

var dbContext = new SampleContext(connectionString);

// Every run starts from the sample data: this deletes and makes again what sample-schema.json lists
// (save the file in the project folder, see Get started).
await dbContext.Direct.ResetAsync();

await new RealCase1_CatchAnInjectionAttempt().RunAsync(dbContext);
RealCase1_CatchAnInjectionAttempt.cs

The sample, as it is in the repository.

using ARX.SDK;
using ARX.SDK.DynamoDb.Services;
using ARX.SDK.Services;

using static ArxSamples.DynamoDb.SampleOutput;

namespace ArxSamples.DynamoDb.Operations.Update.RealCases;

/// <summary>
/// A "profile" endpoint whose posted fields become the attributes to change, attacked two ways: an update expression in
/// a field name, and a field that tries to rewrite the item's key; then the same form used honestly.
/// </summary>
/// <remarks>
/// Names reach DynamoDB only as placeholders (<c>#n0</c>), so a name can't add clauses to the update expression: one
/// with expression syntax is ARX1017 before anything is sent. The table's own key attributes (<c>PK</c>, <c>SK</c>) are
/// ARX's to write, never the caller's.
/// </remarks>
public sealed class RealCase1_CatchAnInjectionAttempt : ISample
{
    public string Name => "update-real-1-catch-an-injection-attempt";

    public string Title => "Catch an injection attempt";

    public async Task RunAsync(SampleContext dbContext)
    {
        var customer = new ArxEntity("customer");
        customer["customer_id"] = "C-D221";
        customer["name"] = "Coho Winery";
        customer["tier"] = "standard";
        await dbContext.Service.CreateAsync(customer);

        await Scenario1_AnExpressionInAFieldNameAsync(dbContext.Service);

        await Scenario2_RewriteTheKeyAsync(dbContext.Service);

        await Scenario3_TheHonestRequestAsync(dbContext.Service);
    }

    private static Task<int> UpdateProfileAsync(ArxDynamoDbService service, Dictionary<string, object> posted)
    {
        var change = new ArxEntity("customer") { RecordId = ArxRecordId.Of("customer_id", "C-D221") };

        foreach (var field in posted)
        {
            change[field.Key] = field.Value;
        }

        return service.UpdateAsync(change);
    }

    /// <summary>1. "name = :v0, tier" tries to set the tier too: ARX1017.</summary>
    private static async Task Scenario1_AnExpressionInAFieldNameAsync(ArxDynamoDbService service)
    {
        Step("1. An expression in a field name");

        try
        {
            await UpdateProfileAsync(service, new() { ["name = :v0, tier"] = "gold" });
        }
        catch (ArxValidationException exception) when (exception.Code == ArxErrorCode.SuspectedInjection)
        {
            ShowError(exception);
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT "tier" FROM "crm" WHERE "PK" = 'CUSTOMER#C-D221' AND "SK" = 'PROFILE'
         * -- Expect: 1 item, tier "standard".
         * ===========================================================
         */
    }

    /// <summary>2. A posted "PK" field: the table's key belongs to ARX, so it's refused.</summary>
    private static async Task Scenario2_RewriteTheKeyAsync(ArxDynamoDbService service)
    {
        Step("2. Rewrite the key");

        try
        {
            await UpdateProfileAsync(service, new() { ["PK"] = "CUSTOMER#someone-else" });
        }
        catch (ArxException exception)
        {
            ShowError(exception);
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT "PK" FROM "crm" WHERE "PK" = 'CUSTOMER#C-D221'
         * -- Expect: 1 item, still under CUSTOMER#C-D221.
         * ===========================================================
         */
    }

    /// <summary>3. The same endpoint, used as meant.</summary>
    private static async Task Scenario3_TheHonestRequestAsync(ArxDynamoDbService service)
    {
        Step("3. The honest request");

        await UpdateProfileAsync(service, new() { ["name"] = "Coho Winery & Vineyard" });

        Show("name changed");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT "name" FROM "crm" WHERE "PK" = 'CUSTOMER#C-D221' AND "SK" = 'PROFILE'
         * -- Expect: 1 item, name "Coho Winery & Vineyard".
         * ===========================================================
         */
    }
}

Expected output

What dotnet run printed when the sample was verified, on a freshly created sample schema. Ids differ when the tables already hold rows.

Output
  > 1. An expression in a field name
      caught ArxValidationException: ARX1017 SuspectedInjection: Attribute name 'name = :v0, tier' looks like an SQL injection attempt (contains '#' or ':' (DynamoDB expression syntax)). ARX refused it before sending anything to the database. Names must come from your code or a fixed list, never from user input.
  > 2. Rewrite the key
      caught ArxValidationException: ARX1001 InvalidArgument: Attribute 'PK' on 'customer' is a key attribute of table 'crm', which ARX writes from the model's templates.
  > 3. The honest request
      name changed