Skip to content

chore: add authorization logic to attestation#1226

Merged
MicBun merged 1 commit intomainfrom
chore/auth-att
Oct 22, 2025
Merged

chore: add authorization logic to attestation#1226
MicBun merged 1 commit intomainfrom
chore/auth-att

Conversation

@outerlook
Copy link
Contributor

@outerlook outerlook commented Oct 22, 2025

Description

  • Added permission validation in the request_attestation action to ensure only wallets with the 'system:network_writer' role can request attestations.
  • Enhanced tests to cover scenarios for both authorized and unauthorized users, ensuring proper error handling for permission violations.
  • Updated the AttestationTestHelper to grant the network_writer role to the deployer by default, facilitating smoother test setups.

Related Problem

How Has This Been Tested?

Summary by CodeRabbit

  • Security

    • Attestation request processing now includes role-based authorization validation.
  • Tests

    • Added authorization test coverage for attestation requests, including both permitted and unauthorized access scenarios.

- Added permission validation in the request_attestation action to ensure only wallets with the 'system:network_writer' role can request attestations.
- Enhanced tests to cover scenarios for both authorized and unauthorized users, ensuring proper error handling for permission violations.
- Updated the AttestationTestHelper to grant the network_writer role to the deployer by default, facilitating smoother test setups.

These changes improve the security and integrity of the attestation request process by enforcing role-based access control.
@outerlook outerlook self-assigned this Oct 22, 2025
@coderabbitai
Copy link

coderabbitai bot commented Oct 22, 2025

Walkthrough

Added a permission check requiring the system:network_writer role to the request_attestation action in the SQL migration. Updated tests to validate both authorized and unauthorized access paths. No changes to public function signatures or exported entities.

Changes

Cohort / File(s) Summary
Permission Check Implementation
internal/migrations/024-attestation-actions.sql
Added role validation logic to request_attestation action that computes the lower-cased caller, iterates through are_members_of('system', 'network_writer', [caller]), and raises an error if no active member is found. Check executes immediately after transaction ID capture and before encryption flag validation.
Test Coverage
tests/streams/attestation/attestation_request_test.go
Added two subtests to TestRequestAttestationInsertsCanonicalPayload: "HappyPath" (existing flow) and "UnauthorizedUserBlocked" (new unauthorized path). Introduced runAttestationUnauthorizedBlocked helper that constructs an unauthorized context, invokes request_attestation, and verifies error contains expected authorization message.
Test Helpers
tests/streams/attestation/test_helpers.go
Added public method GrantNetworkWriterRole(walletAddr string) to AttestationTestHelper. Updated NewAttestationTestHelper to grant the deployer the network_writer role by default. Modified CreateAttestationForRequester to grant the role to requester before calling request_attestation.

Sequence Diagram

sequenceDiagram
    actor User
    participant Engine
    participant DB as Database
    participant RoleCheck as Role Validator

    User->>Engine: request_attestation(args)
    activate Engine
    Engine->>Engine: Capture transaction ID
    
    rect rgb(220, 240, 255)
    Note over Engine,RoleCheck: NEW: Permission Check
    Engine->>RoleCheck: Check if caller has<br/>system:network_writer role
    RoleCheck->>DB: Query are_members_of()
    DB-->>RoleCheck: Member status
    alt Role Not Found / Inactive
        RoleCheck-->>Engine: Authorization Error
        Engine-->>User: ❌ Missing Role Error
    else Role Verified & Active
        RoleCheck-->>Engine: ✓ Authorized
    end
    end
    
    rect rgb(240, 255, 240)
    Note over Engine,DB: Existing Flow
    Engine->>Engine: Validate encryption flag
    Engine->>Engine: Check action allowlist
    Engine->>DB: Execute & attest
    DB-->>Engine: ✓ Success
    end
    
    Engine-->>User: ✓ Attestation Created
    deactivate Engine
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Changes are focused and follow a consistent pattern across files. The permission check logic is straightforward validation applied early in the request flow. Test additions clearly mirror the implementation pattern (authorized + unauthorized paths).

Possibly related PRs

Suggested labels

type: chore

Suggested reviewers

  • MicBun

Poem

🐰 A role check now guards the gate,
No more free attestations—fate
Reserved for network_writers true,
DDoS kept at bay, through and through!
Authorization's gentle shield,
Makes the attestation field more sealed. ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "chore: add authorization logic to attestation" accurately and concisely summarizes the main change in the changeset. The primary modifications add a permission check requiring the system:network_writer role for attestation requests, which directly aligns with the title's description of adding authorization logic. The title is clear, specific, and appropriately scoped without unnecessary noise.
Linked Issues Check ✅ Passed The code changes directly address all primary coding objectives from linked issue #1223. The migration file implements a permission check requiring the system:network_writer role in the request_attestation action, preventing arbitrary parties from requesting attestations [#1223]. The test file adds both authorized and unauthorized test scenarios to verify proper authorization enforcement [#1223]. The test helper introduces a GrantNetworkWriterRole method to facilitate role assignment during test setup, enabling the gating mechanism specified in the issue [#1223]. All changes align with the goal of using the existing Roles mechanism as an interim protection measure.
Out of Scope Changes Check ✅ Passed All modifications in the changeset are directly scoped to implementing the attestation authorization requirement from issue #1223. The migration adds the authorization check to the request_attestation action, the test file adds comprehensive test coverage for both authorized and unauthorized paths, and the test helper introduces supporting utilities for role management in tests. No changes appear to address unrelated features or introduce tangential modifications beyond the stated objective of gating attestation requests via roles.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/auth-att

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
internal/migrations/024-attestation-actions.sql (1)

25-37: Permission check is correctly placed and secure.

The authorization logic correctly:

  • Executes before validation and expensive operations (good fail-fast placement)
  • Normalizes the caller address for case-insensitive comparison
  • Provides a clear error message without leaking sensitive information

The loop-and-break pattern is functional, though it could optionally be simplified. Consider this alternative for slightly cleaner code:

-    -- Permission Check: Ensure caller has the 'system:network_writer' role.
-    $lower_caller TEXT := LOWER(@caller);
-    $has_permission BOOL := false;
-    for $row in are_members_of('system', 'network_writer', ARRAY[$lower_caller]) {
-        if $row.wallet = $lower_caller AND $row.is_member {
-            $has_permission := true;
-            break;
-        }
-    }
-    if NOT $has_permission {
-        ERROR('Caller does not have the required system:network_writer role to request attestation.');
-    }
+    -- Permission Check: Ensure caller has the 'system:network_writer' role.
+    $lower_caller TEXT := LOWER(@caller);
+    $has_permission BOOL := EXISTS(
+        SELECT 1 FROM are_members_of('system', 'network_writer', ARRAY[$lower_caller])
+        WHERE wallet = $lower_caller AND is_member
+    );
+    if NOT $has_permission {
+        ERROR('Caller does not have the required system:network_writer role to request attestation.');
+    }
tests/streams/attestation/attestation_request_test.go (1)

135-171: LGTM! Thorough authorization test.

The unauthorized user test correctly:

  • Creates a user without the network_writer role
  • Attempts to request attestation with otherwise valid parameters
  • Verifies the error is returned at the action level (not engine level)
  • Checks for the specific authorization error message

The test provides good coverage of the negative authorization path. Consider optionally adding a database assertion to verify no attestation row was created, though the early error in the SQL function makes this implicit:

// Optional: Verify no attestation was created
var count int
err = platform.Engine.Execute(helper.NewEngineContext(), platform.DB,
    `SELECT COUNT(*) FROM attestations WHERE requester = $req`,
    map[string]any{"req": unauthorizedAddr.Bytes()},
    func(row *common.Row) error {
        count = int(row.Values[0].(int64))
        return nil
    })
require.NoError(t, err)
require.Equal(t, 0, count, "no attestation should be created for unauthorized user")
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c18e7f0 and f46efb0.

📒 Files selected for processing (3)
  • internal/migrations/024-attestation-actions.sql (2 hunks)
  • tests/streams/attestation/attestation_request_test.go (2 hunks)
  • tests/streams/attestation/test_helpers.go (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
tests/streams/attestation/attestation_request_test.go (2)
tests/streams/attestation/test_helpers.go (4)
  • TestActionIDRequest (25-25)
  • AttestationTestHelper (69-73)
  • TestDataProviderHex (29-29)
  • TestStreamID (28-28)
extensions/tn_utils/serialization.go (1)
  • EncodeActionArgs (45-76)
tests/streams/attestation/test_helpers.go (1)
tests/streams/utils/setup/roles.go (1)
  • AddMemberToRoleBypass (73-98)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: lint
  • GitHub Check: acceptance-test
🔇 Additional comments (5)
internal/migrations/024-attestation-actions.sql (1)

8-10: LGTM!

The permission documentation is clear and accurately describes the new authorization requirement.

tests/streams/attestation/test_helpers.go (3)

77-88: LGTM! Smart default for test setup.

Automatically granting the network_writer role to the deployer in NewAttestationTestHelper is a good design choice that:

  • Simplifies the happy path for most tests
  • Reduces boilerplate in existing tests
  • Keeps unauthorized test scenarios explicit (requiring manual setup)

This aligns well with the PR's goal of adding authorization as an interim protection measure.


215-219: LGTM!

The GrantNetworkWriterRole method provides a clean interface for test setup. Using AddMemberToRoleBypass with authorization override is appropriate for test helpers.


223-224: LGTM! Good defensive test design.

Granting the network_writer role before requesting attestation in CreateAttestationForRequester ensures that tests using this helper don't fail due to authorization issues unless they're specifically testing authorization.

tests/streams/attestation/attestation_request_test.go (1)

37-43: LGTM! Clean test organization.

The subtest structure clearly separates the happy path from the authorization test case, making test intent explicit and improving test output readability.

@holdex
Copy link

holdex bot commented Oct 22, 2025

Time Submission Status

Member Status Time Action Last Update
@outerlook ❌ Missing - ⚠️ Submit time -
MicBun ✅ Submitted 15min Update time Oct 23, 2025, 7:54 AM

@outerlook outerlook requested a review from MicBun October 22, 2025 15:26
Copy link
Member

@MicBun MicBun left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@MicBun MicBun merged commit 9f0df0d into main Oct 22, 2025
6 of 7 checks passed
@MicBun MicBun deleted the chore/auth-att branch October 22, 2025 15:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Problem: producing attestations is not gated

2 participants