Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions be/src/adsense/audit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
getIdentifierFromClaimInfo,
messageDigest,
} from "../reclaim/claim-digest.js";
import { AuditError, auditRevenueProof, formatFieldReport, recoverSigner, type RevenueProof } from "./audit.js";
import { AuditError, auditRevenueProof, formatFieldReport, recoverSigner, type AuditExpectations, type RevenueProof } from "./audit.js";
import { CONTEXT_MESSAGE, buildRevenueRequest, type RevenueWindow } from "./request.js";

const PUB = "pub-1234567890123456";
Expand Down Expand Up @@ -77,7 +77,7 @@ function makeProof(o: Overrides = {}): RevenueProof {

const expectations = { publisherId: PUB, stellarAddress: ALICE, window: Q3, accessToken: TOKEN, now: NOW, attestor: ATTESTOR };

function failuresOf(proof: RevenueProof, expect = expectations): string[] {
function failuresOf(proof: RevenueProof, expect: AuditExpectations = expectations): string[] {
try {
auditRevenueProof(proof, expect);
} catch (e) {
Expand Down Expand Up @@ -188,3 +188,11 @@ test("a stale or future-dated claim fails", () => {
assert.ok(failuresOf(makeProof({ timestampS: nowS - 8 * 86_400 })).some((m) => /older than/.test(m)));
assert.ok(failuresOf(makeProof({ timestampS: nowS + 3600 })).some((m) => /future/.test(m)));
});

test("with the app id given, a claim requested through another Reclaim app fails (#102)", () => {
const app = "0x96FAF173BB7171A530B3E44F35F32D1307BDA4FA";
assert.deepEqual(failuresOf(makeProof(), { ...expectations, owner: app }), []);
const other = failuresOf(makeProof(), { ...expectations, owner: "0x6415200c713135e77157e1536d488df4f2bb7d04" });
assert.equal(other.length, 1);
assert.match(other[0], /not the Reclaim app .* the contract pins/);
});
16 changes: 13 additions & 3 deletions be/src/adsense/audit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ export interface AuditExpectations {
maxAgeS?: number;
/** Expected signer. Defaults to the production attestor; tests pass a throwaway key. */
attestor?: string;
/**
* The Reclaim app id the proof was requested with, which the attestor signs as `owner`
* and the contract pins (#102). When given, a claim with any other owner fails here
* instead of as `VerifierRejected` on chain.
*/
owner?: string;
}

export interface FieldReport {
Expand Down Expand Up @@ -299,9 +305,13 @@ export function auditRevenueProof(proof: RevenueProof, expect: AuditExpectations
} else fail("context.providerHash is not a 32-byte hex hash");

// 5. owner, timestamp, epoch.
if (/^0x[0-9a-f]{40}$/.test(claim.owner)) {
ok("owner", claim.owner, "Address of the key zkFetch signed the request with. Public by construction.");
} else fail(`owner is not a lowercase 20-byte address: ${claim.owner}`);
if (!/^0x[0-9a-f]{40}$/.test(claim.owner)) {
fail(`owner is not a lowercase 20-byte address: ${claim.owner}`);
} else if (expect.owner && claim.owner !== expect.owner.toLowerCase()) {
fail(`owner is ${claim.owner}, not the Reclaim app ${expect.owner.toLowerCase()} the contract pins (#102)`);
} else {
ok("owner", claim.owner, "The Reclaim app the proof was requested with, which the contract pins (#102). Public by construction.");
}

const nowS = Math.floor(now.getTime() / 1000);
const maxAge = expect.maxAgeS ?? 7 * 86_400;
Expand Down
1 change: 1 addition & 0 deletions be/src/api/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ function relay(): Prover | undefined {
}
const client = new ReclaimClient(appId, appSecret, false, 2);
const deps = {
owner: appId,
google: googleGet,
zkFetch: ((url, options, secretOptions) => client.zkFetch(url, { ...options, zkEngine: ZK_ENGINE }, secretOptions)) as Parameters<
typeof proveRevenue
Expand Down
1 change: 1 addition & 0 deletions be/src/cli/prove-adsense.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ async function main() {
try {
proven = await proveRevenue(
{
owner: env.appId,
google: googleGet,
zkFetch: (url, options, secretOptions) => client.zkFetch(url, { ...options, zkEngine: ZK_ENGINE }, secretOptions),
months: env.months,
Expand Down
6 changes: 6 additions & 0 deletions be/src/relay/prove.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,9 @@ test("a C… or malformed borrower is refused before anything is read", async ()
await assert.rejects(proveRevenue(deps({ google }), { borrower: "GABC", accessToken: TOKEN }), /not a Stellar account/);
assert.equal(google.calls.length, 0);
});

test("a proof whose owner is not this relay's Reclaim app is refused by the audit (#102)", async () => {
const other = "0x6415200c713135e77157e1536d488df4f2bb7d04";
assert.equal(await code(proveRevenue(deps({ owner: other }), { borrower: ALICE, accessToken: TOKEN })), "audit");
await proveRevenue(deps({ owner: "0x96faf173bb7171a530b3e44f35f32d1307bda4fa" }), { borrower: ALICE, accessToken: TOKEN });
});
3 changes: 3 additions & 0 deletions be/src/relay/prove.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export interface ProveDeps {
months?: number;
/** Expected signer. Defaults to the production attestor; tests pass a throwaway key. */
attestor?: string;
/** The Reclaim app id proofs are requested with: the `owner` the contract pins (#102). */
owner?: string;
}

export interface ProveInput {
Expand Down Expand Up @@ -98,6 +100,7 @@ export async function proveRevenue(deps: ProveDeps, input: ProveInput, onStep: (
now: deps.now?.(),
maxAgeS: MAX_AGE_S,
attestor: deps.attestor,
owner: deps.owner,
});
} catch (e) {
throw new ProveError("audit", (e as Error).message);
Expand Down
6 changes: 6 additions & 0 deletions docs/interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ sign_data = identifier \n owner_lowercase \n timestamp_s \n epoch
digest = keccak256("\x19Ethereum Signed Message:\n" + len(sign_data) + sign_data)
```

**`owner` is the Reclaim app that requested the proof, not the borrower** (#102). A real attestor
sets it to the app id the relay proves with (`RECLAIM_APP_ID`), so the contract cannot rebuild it from
the claim and pins it instead (`set_claim_owner`). The borrower is bound by `contextAddress`, inside
`identifier`, and never was by `owner`.

**The revenue figure is not a signed field.** It lives in `context` and reaches the signature only
through `identifier`. Nothing may trust a figure that was not fed into the identifier computation.

Expand All @@ -52,6 +57,7 @@ vary.
| `provider` | constant `"http"` | Reclaim's HTTP provider |
| `parameters_template` | **admin, `set_claim_template`** | The exact bytes come from the first live proof (#5) |
| `provider_hash` | **admin, same call** | Reclaim's provider hash for the AdSense provider |
| `claim_owner` | **admin, `set_claim_owner`** | The attestor's `owner`: Forepay's Reclaim app id, lowercase (#102). Absent means the borrower, which only the rehearsal's test witness signs |

`set_claim_template` is admin-gated and may be called again — the template changes whenever the
provider version changes. It does **not** invalidate existing advances; it only governs what a new
Expand Down
8 changes: 8 additions & 0 deletions sc/advance/src/claim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,14 @@ pub fn borrower_bytes(env: &Env, borrower: &Address) -> Option<Bytes> {
string_bytes(env, &borrower.to_string())
}

/// `0x` followed by exactly 40 hex digits, either case: the shape of a Reclaim owner.
pub fn is_eth_address(b: &Bytes) -> bool {
if b.len() != 42 || b.get(0) != Some(b'0') || b.get(1) != Some(b'x') {
return false;
}
(2..42).all(|i| matches!(b.get(i), Some(c) if c.is_ascii_hexdigit()))
}

/// ASCII-lowercase a byte string.
///
/// Reclaim lowercases `owner` before signing, so the digest must be built from the
Expand Down
53 changes: 50 additions & 3 deletions sc/advance/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ pub enum DataKey {
/// One advance, keyed by the nullifier that funded it. Persistent: an advance that
/// vanished when its TTL lapsed would erase a debt, which is not a rounding error.
Advance(BytesN<32>),
/// The attestor's `owner` every claim must carry: the Reclaim app the relay proves
/// with, `0x…`, lowercase (#102). Absent means the borrower, which is what the
/// rehearsal's test witness signs; no real attestor claim has that owner.
ClaimOwner,
}

/// An advance that has been paid out, and what is still owed on it.
Expand Down Expand Up @@ -285,6 +289,13 @@ pub struct ClaimTemplateSet {
pub parts: u32,
}

#[contractevent]
pub struct ClaimOwnerSet {
#[topic]
pub admin: Address,
pub owner: Bytes,
}

#[contractevent]
pub struct NullifierSpent {
#[topic]
Expand Down Expand Up @@ -508,6 +519,37 @@ impl AdvanceContract {
env.storage().instance().get(&DataKey::ProviderHash)
}

/// Pin the attestor's `owner`: the Reclaim app id the relay proves with (#102).
///
/// A real attestor signs `identifier \n owner \n timestamp \n epoch` with `owner` set
/// to the **requesting app's** address, not to anything in the claim. The contract
/// cannot read it from the claim, because it rebuilds the digest rather than trusting
/// one, so it has to be pinned like the template. Pinning it also refuses claims made
/// through any other Reclaim app.
///
/// It carries no part of the borrower binding: that lives in `contextAddress`, inside
/// the identifier, and is unaffected.
///
/// `owner` must be `0x` and 40 hex digits. It is stored lowercased, because Reclaim
/// lowercases it before signing.
pub fn set_claim_owner(env: Env, owner: Bytes) -> Result<(), Error> {
let admin = Self::require_admin(&env)?;
if !claim::is_eth_address(&owner) {
return Err(Error::ClaimMismatch);
}
let owner = claim::lowercase(&env, &owner);
env.storage().instance().set(&DataKey::ClaimOwner, &owner);
Self::bump(&env);

ClaimOwnerSet { admin, owner }.publish(&env);
Ok(())
}

/// The pinned owner, if one is set. Absent means the borrower (the rehearsal's form).
pub fn claim_owner(env: Env) -> Option<Bytes> {
env.storage().instance().get(&DataKey::ClaimOwner)
}

// -------------------------------------------------- verify a claim (#9)

/// Check a Reclaim proof and return only what it actually attested.
Expand Down Expand Up @@ -574,9 +616,14 @@ impl AdvanceContract {
let identifier = claim::identifier(&env, &parameters, &context);
let identifier_hex = claim::hex_prefixed(&identifier);

// The attestor's `owner` is the borrower's own address, lowercased, because that
// is what the relay put in the claim. Reclaim lowercases it before signing.
let owner = claim::lowercase(&env, &borrower_b);
// The attestor's `owner` is the Reclaim app that requested the proof, pinned by the
// admin (#102). Before #102 this was the borrower, which no real attestor claim
// carries; that form survives only where nothing is pinned, for the rehearsal's
// test witness. Reclaim lowercases the owner before signing.
let owner: Bytes = match env.storage().instance().get(&DataKey::ClaimOwner) {
Some(pinned) => pinned,
None => claim::lowercase(&env, &borrower_b),
};
let digest = claim::message_digest(&env, &identifier_hex, &owner, timestamp_s, epoch);

let verifier: Address = env
Expand Down
127 changes: 125 additions & 2 deletions sc/advance/src/test_claim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ pub(crate) const TIMESTAMP_S: u64 = 1_760_000_000;
pub(crate) const EPOCH: u64 = 1;
const SIGNATURE_HEX: &str = "0a1607562845069dcd91874ae32ffc55d2ce799078af623b8300c1765137ca0f577ba3ed8dc8895867e717734d9535536384718e77126229ed28327c54cf202f";
pub(crate) const RECOVERY_ID: u32 = 1;
/// The same claim, signed the way a real attestor signs it: with `owner` set to the
/// requesting Reclaim app rather than the borrower (#102). From the fixture's `appOwner*`.
const APP_OWNER: &str = "0x6415200c713135e77157e1536d488df4f2bb7d04";
const APP_SIGNATURE_HEX: &str = "be04cabf370de372ce48726350419d76169f5b35fa64ba03ffb5db5b1a5a4a6a773196501dcfd7a42b94a1a510c9aaa0ff5536cb37ed0ada1f917415da9e96c7";
const APP_RECOVERY_ID: u32 = 0;
/// The address the fixture's signature recovers to.
const SIGNER: [u8; 20] = [
0x19, 0xe7, 0xe3, 0x76, 0xe7, 0xc2, 0x13, 0xb7, 0xe7, 0xe7, 0xe4, 0x6c, 0xc7, 0x0a, 0x5d, 0xd0,
Expand Down Expand Up @@ -160,10 +165,14 @@ fn setup() -> Fixture {
}

pub(crate) fn signature(env: &Env) -> BytesN<64> {
signature_from(env, SIGNATURE_HEX)
}

fn signature_from(env: &Env, hex: &str) -> BytesN<64> {
let mut raw = [0u8; 64];
for (i, b) in raw.iter_mut().enumerate() {
let hi = SIGNATURE_HEX.as_bytes()[i * 2];
let lo = SIGNATURE_HEX.as_bytes()[i * 2 + 1];
let hi = hex.as_bytes()[i * 2];
let lo = hex.as_bytes()[i * 2 + 1];
let v = |c: u8| if c >= b'a' { c - b'a' + 10 } else { c - b'0' };
*b = (v(hi) << 4) | v(lo);
}
Expand Down Expand Up @@ -413,6 +422,120 @@ fn a_template_with_the_wrong_number_of_parts_is_refused() {
);
}

// --- #102: the attestor's owner is the app, pinned, not the borrower ---

/// `verify_claim` on the fixture signed with the app as owner.
fn verify_app_signed(f: &Fixture) -> Result<VerifiedClaim, Error> {
match f.client.try_verify_claim(
&f.borrower,
&String::from_str(&f.env, REVENUE),
&String::from_str(&f.env, PUB_ID),
&String::from_str(&f.env, WINDOW_START),
&String::from_str(&f.env, WINDOW_END),
&TIMESTAMP_S,
&EPOCH,
&signature_from(&f.env, APP_SIGNATURE_HEX),
&APP_RECOVERY_ID,
) {
Ok(Ok(claim)) => Ok(claim),
Err(Ok(e)) => Err(e),
other => panic!("unexpected host-level result: {other:?}"),
}
}

#[test]
fn without_a_pinned_owner_a_claim_signed_as_a_real_attestor_signs_is_refused() {
// The #102 bug, kept as a test: rebuilding the owner from the borrower cannot match a
// claim whose owner is the requesting app, which is every real attestor claim.
let f = setup();
assert_eq!(verify_app_signed(&f), Err(Error::VerifierRejected));
}

#[test]
fn with_the_app_pinned_as_owner_that_claim_verifies() {
let f = setup();
f.client
.set_claim_owner(&Bytes::from_slice(&f.env, APP_OWNER.as_bytes()));
let claim = verify_app_signed(&f).expect("a claim signed for the pinned app must verify");
assert_eq!(claim.borrower, f.borrower);
}

#[test]
fn with_the_app_pinned_a_claim_signed_for_the_borrower_is_refused() {
let f = setup();
f.client
.set_claim_owner(&Bytes::from_slice(&f.env, APP_OWNER.as_bytes()));
assert!(verify(&f, REVENUE, PUB_ID, &f.borrower).is_err());
}

#[test]
fn the_borrower_binding_survives_the_pinned_owner() {
// The owner is the app for everyone, so it cannot be what binds the borrower. The
// context still does: another address changes the identifier.
let f = setup();
f.client
.set_claim_owner(&Bytes::from_slice(&f.env, APP_OWNER.as_bytes()));
let attacker = Address::generate(&f.env);
let out = f.client.try_verify_claim(
&attacker,
&String::from_str(&f.env, REVENUE),
&String::from_str(&f.env, PUB_ID),
&String::from_str(&f.env, WINDOW_START),
&String::from_str(&f.env, WINDOW_END),
&TIMESTAMP_S,
&EPOCH,
&signature_from(&f.env, APP_SIGNATURE_HEX),
&APP_RECOVERY_ID,
);
assert_eq!(out, Err(Ok(Error::VerifierRejected)));
}

#[test]
fn the_owner_is_stored_lowercase_and_must_look_like_one() {
let f = setup();
let upper = APP_OWNER.to_uppercase().replacen("0X", "0x", 1);
f.client
.set_claim_owner(&Bytes::from_slice(&f.env, upper.as_bytes()));
assert_eq!(
f.client.claim_owner(),
Some(Bytes::from_slice(&f.env, APP_OWNER.as_bytes()))
);
assert!(verify_app_signed(&f).is_ok());

for bad in [
"6415200c713135e77157e1536d488df4f2bb7d04",
"0x6415200c713135e77157e1536d488df4f2bb7d0",
"0x6415200c713135e77157e1536d488df4f2bb7d0g",
"GA2CD6PMHMBTCFAQDO3R22BSZN5ZSVTAKVNOKXL2SONZBLGRAYIOWWH2",
] {
assert_eq!(
f.client
.try_set_claim_owner(&Bytes::from_slice(&f.env, bad.as_bytes())),
Err(Ok(Error::ClaimMismatch)),
"{bad}"
);
}
}

#[test]
fn only_the_admin_can_pin_the_owner() {
let env = Env::default();
let id = env.register(
AdvanceContract,
(
Address::generate(&env),
Address::generate(&env),
Address::generate(&env),
),
);
let client = AdvanceContractClient::new(&env, &id);
// No auth mocked: require_auth must bite.
assert!(client
.try_set_claim_owner(&Bytes::from_slice(&env, APP_OWNER.as_bytes()))
.is_err());
assert_eq!(client.claim_owner(), None);
}

// --- #10: the nullifier registry ---

fn reserve(f: &Fixture, borrower: &Address) -> Result<VerifiedClaim, ()> {
Expand Down
Loading