diff --git a/dark-tariff/backend/app/api/routes/reports.py b/dark-tariff/backend/app/api/routes/reports.py index 46d7464..7770740 100755 --- a/dark-tariff/backend/app/api/routes/reports.py +++ b/dark-tariff/backend/app/api/routes/reports.py @@ -22,6 +22,8 @@ async def finance_summary(period: str | None = None, fields: list[str] = Query(d @router.post("/export") async def export_report(body: ReportQueryIn): + if body.report != "finance": + raise QueryError("P0400", "Unknown report type.") fields = body.fields if not fields: fields = [field["id"] for field in await operations.report_fields(body.report)] diff --git a/dark-tariff/backend/app/db/operations.py b/dark-tariff/backend/app/db/operations.py index 31418b7..75080de 100755 --- a/dark-tariff/backend/app/db/operations.py +++ b/dark-tariff/backend/app/db/operations.py @@ -1,9 +1,7 @@ -import asyncio import base64 import secrets import psycopg -from argon2.low_level import Type, hash_secret_raw from psycopg.types.json import Jsonb from backend.app.db import connection @@ -19,10 +17,7 @@ async def reading_public(reading_id): return await call("select billing.reading_public(%s::bigint)", (reading_id,)) def calculation_key(reading_id): - value = f"{reading_id}|{secrets.randbelow(10000):04d}".encode("ascii") - key = hash_secret_raw(value, bytes(16), time_cost=1, memory_cost=8192, - parallelism=1, hash_len=32, type=Type.ID, version=19) - return base64.b64encode(key).decode("ascii") + return base64.b64encode(secrets.token_bytes(32)).decode("ascii") async def add_reading(serial, kind, metrics): try: @@ -33,7 +28,7 @@ async def add_reading(serial, kind, metrics): (serial, kind, Jsonb(metrics)), ) reading = (await cursor.fetchone())[0] - key = await asyncio.to_thread(calculation_key, reading["id"]) + key = calculation_key(reading["id"]) cursor = await db.execute( "select billing.receipt_issue(r, %s::text)" " from billing.reading r where r.id = %s::bigint", diff --git a/dark-tariff/backend/database/sql/functions/checks.sql b/dark-tariff/backend/database/sql/functions/checks.sql index 6918fa0..986fe91 100755 --- a/dark-tariff/backend/database/sql/functions/checks.sql +++ b/dark-tariff/backend/database/sql/functions/checks.sql @@ -27,10 +27,9 @@ declare begin loop v := get_byte(gen_random_bytes(1), 0); - exit when v < 200; + exit when v < 252; end loop; - v := v % 100; - return case when v < 70 then 0 when v < 95 then 1 else 2 end; + return v % 3; end; $$; @@ -129,11 +128,25 @@ create or replace function chat.check_start(p_reading bigint) returns jsonb language plpgsql as $$ declare v_id uuid; + v_failed integer; + v_active integer; begin - perform 1 from billing.reading where id = p_reading and created_at > now() - interval '10 minutes' for key share; + select failed_checks into v_failed + from billing.reading + where id = p_reading and created_at > now() - interval '10 minutes' + for update; if not found then raise exception 'Reading not found.' using errcode = 'P0404'; end if; + if v_failed >= 4 then + raise exception 'Too many failed verification attempts.' using errcode = 'P0403'; + end if; + select count(*) into v_active + from chat.check_session + where reading_id = p_reading and not complete; + if v_active >= 2 then + raise exception 'Another verification is already in progress.' using errcode = 'P0409'; + end if; insert into chat.check_session (reading_id) values (p_reading) returning id into v_id; return jsonb_build_object('id', v_id, 'round', 1, 'stage', 'commit', 'message', 'Step 1 of 10. Submit three values.'); @@ -185,6 +198,7 @@ begin end if; if not coalesce(chat.valid_response(v_reading, v_session.data, v_session.challenge, p_data), false) then delete from chat.check_session where id = p_id; + update billing.reading set failed_checks = failed_checks + 1 where id = v_session.reading_id; return jsonb_build_object('stage', 'failed', 'message', 'Verification failed. Try again.'); end if; if p_round = 10 then diff --git a/dark-tariff/backend/database/sql/functions/reports.sql b/dark-tariff/backend/database/sql/functions/reports.sql index 0a0b579..da71712 100755 --- a/dark-tariff/backend/database/sql/functions/reports.sql +++ b/dark-tariff/backend/database/sql/functions/reports.sql @@ -4,6 +4,279 @@ language sql stable as $$ from billing.report_field where report_types @> array[p_report] $$; +create or replace function billing._parse_predicate_term( + p_types text[], p_vals text[], inout p_pos integer, p_mode text, p_depth integer, out p_sql text +) +language plpgsql immutable as $$ +declare + v_has_not boolean := false; + v_col text; + v_col_sql text; + v_op text; + v_lit text; + v_inner text; +begin + if p_depth > 16 then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + if p_pos <= coalesce(cardinality(p_types), 0) and p_types[p_pos] = 'KW' and p_vals[p_pos] = 'not' then + v_has_not := true; + p_pos := p_pos + 1; + end if; + if p_pos > coalesce(cardinality(p_types), 0) then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + if p_types[p_pos] = 'LPAREN' then + p_pos := p_pos + 1; + select r.p_sql, r.p_pos into v_inner, p_pos + from billing._parse_predicate_expr(p_types, p_vals, p_pos, p_mode, p_depth + 1) r; + if p_pos > coalesce(cardinality(p_types), 0) or p_types[p_pos] <> 'RPAREN' then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + p_pos := p_pos + 1; + p_sql := '(' || v_inner || ')'; + elsif p_types[p_pos] = 'BOOL' then + p_sql := p_vals[p_pos]; + p_pos := p_pos + 1; + elsif p_types[p_pos] = 'IDENT' then + v_col := p_vals[p_pos]; + p_pos := p_pos + 1; + if v_col in ('period', 'resource', 'tariff') then + v_col_sql := format('dimensions.%I', v_col); + elsif p_mode = 'having' and v_col = 'quantity' then + v_col_sql := $expr$sum((c.data->'calculation'->>'quantity')::numeric)$expr$; + elsif p_mode = 'having' and v_col = 'amount' then + v_col_sql := $expr$sum((c.data->'calculation'->>'amount')::numeric)$expr$; + elsif p_mode = 'having' and v_col = 'readings' then + v_col_sql := 'count(*)'; + else + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + if p_pos > coalesce(cardinality(p_types), 0) then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + if p_types[p_pos] = 'KW' and p_vals[p_pos] = 'not' then + p_pos := p_pos + 1; + if p_pos > coalesce(cardinality(p_types), 0) or p_types[p_pos] <> 'OP' + or p_vals[p_pos] not in ('like', 'ilike') then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + v_op := 'not ' || p_vals[p_pos]; + elsif p_types[p_pos] = 'OP' then + v_op := p_vals[p_pos]; + else + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + p_pos := p_pos + 1; + if p_pos > coalesce(cardinality(p_types), 0) then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + if p_types[p_pos] = 'STR' then + v_lit := quote_literal(p_vals[p_pos]); + elsif p_types[p_pos] = 'NUM' then + v_lit := p_vals[p_pos]; + else + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + p_pos := p_pos + 1; + p_sql := v_col_sql || ' ' || v_op || ' ' || v_lit; + else + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + if v_has_not then + p_sql := '(not ' || p_sql || ')'; + end if; +end; +$$; + +create or replace function billing._parse_predicate_expr( + p_types text[], p_vals text[], inout p_pos integer, p_mode text, p_depth integer, out p_sql text +) +language plpgsql immutable as $$ +declare + v_kw text; + v_rhs text; +begin + if p_depth > 16 then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + select r.p_sql, r.p_pos into p_sql, p_pos + from billing._parse_predicate_term(p_types, p_vals, p_pos, p_mode, p_depth) r; + while p_pos <= coalesce(cardinality(p_types), 0) + and p_types[p_pos] = 'KW' and p_vals[p_pos] in ('and', 'or') loop + v_kw := p_vals[p_pos]; + p_pos := p_pos + 1; + select r.p_sql, r.p_pos into v_rhs, p_pos + from billing._parse_predicate_term(p_types, p_vals, p_pos, p_mode, p_depth) r; + p_sql := '(' || p_sql || ' ' || v_kw || ' ' || v_rhs || ')'; + end loop; +end; +$$; + +create or replace function billing.sanitize_predicate(p_expr text, p_mode text) returns text +language plpgsql immutable as $$ +declare + v_len integer; + v_i integer := 1; + v_ch text; + v_two text; + v_buf text; + v_closed boolean; + v_word text; + v_num text; + v_types text[] := '{}'; + v_vals text[] := '{}'; + v_pos integer := 1; + v_sql text; +begin + if p_expr is null or btrim(p_expr) = '' then + return 'true'; + end if; + if length(p_expr) > 1024 then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + v_len := length(p_expr); + while v_i <= v_len loop + v_ch := substr(p_expr, v_i, 1); + if v_ch ~ '^\s$' then + v_i := v_i + 1; + elsif v_ch = '(' then + v_types := array_append(v_types, 'LPAREN'); + v_vals := array_append(v_vals, '('); + v_i := v_i + 1; + elsif v_ch = ')' then + v_types := array_append(v_types, 'RPAREN'); + v_vals := array_append(v_vals, ')'); + v_i := v_i + 1; + elsif v_ch = '''' then + v_i := v_i + 1; + v_buf := ''; + v_closed := false; + while v_i <= v_len loop + v_ch := substr(p_expr, v_i, 1); + if v_ch = '''' then + if v_i < v_len and substr(p_expr, v_i + 1, 1) = '''' then + v_buf := v_buf || ''''; + v_i := v_i + 2; + else + v_closed := true; + v_i := v_i + 1; + exit; + end if; + else + v_buf := v_buf || v_ch; + v_i := v_i + 1; + end if; + end loop; + if not v_closed then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + v_types := array_append(v_types, 'STR'); + v_vals := array_append(v_vals, v_buf); + elsif v_i < v_len and substr(p_expr, v_i, 2) in ('<=', '>=', '<>', '!=') then + v_two := substr(p_expr, v_i, 2); + v_types := array_append(v_types, 'OP'); + v_vals := array_append(v_vals, v_two); + v_i := v_i + 2; + elsif v_ch in ('=', '<', '>') then + v_types := array_append(v_types, 'OP'); + v_vals := array_append(v_vals, v_ch); + v_i := v_i + 1; + elsif v_ch ~ '^[0-9]$' or (v_ch = '-' and v_i < v_len and substr(p_expr, v_i + 1, 1) ~ '^[0-9]$') then + v_num := (regexp_match(substr(p_expr, v_i), '^(-?[0-9]+(?:\.[0-9]+)?)'))[1]; + if v_num is null then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + v_types := array_append(v_types, 'NUM'); + v_vals := array_append(v_vals, v_num); + v_i := v_i + length(v_num); + elsif v_ch ~ '^[A-Za-z_]$' then + v_word := lower((regexp_match(substr(p_expr, v_i), '^([A-Za-z_][A-Za-z0-9_]*)'))[1]); + v_i := v_i + length(v_word); + if v_word in ('and', 'or', 'not') then + v_types := array_append(v_types, 'KW'); + elsif v_word in ('like', 'ilike') then + v_types := array_append(v_types, 'OP'); + elsif v_word in ('true', 'false') then + v_types := array_append(v_types, 'BOOL'); + else + v_types := array_append(v_types, 'IDENT'); + end if; + v_vals := array_append(v_vals, v_word); + else + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + end loop; + if coalesce(cardinality(v_types), 0) = 0 then + return 'true'; + end if; + select r.p_sql, r.p_pos into v_sql, v_pos + from billing._parse_predicate_expr(v_types, v_vals, v_pos, p_mode, 0) r; + if v_pos <> cardinality(v_types) + 1 then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + return v_sql; +end; +$$; + +create or replace function billing.sanitize_group_by(p_group_by text) returns text +language plpgsql stable as $$ +declare + v_item text; + v_col text; + v_parts text[] := '{}'; +begin + if p_group_by is null or btrim(p_group_by) = '' then + return 'dimensions.period, dimensions.resource, dimensions.tariff'; + end if; + foreach v_item in array string_to_array(p_group_by, ',') loop + v_col := lower(btrim(v_item)); + if v_col = '' or not exists ( + select 1 from billing.report_field + where id = v_col and report_types @> array['finance'] and not aggregate + ) then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + v_parts := array_append(v_parts, format('dimensions.%I', v_col)); + end loop; + return array_to_string(v_parts, ', '); +end; +$$; + +create or replace function billing.sanitize_sort(p_sort text) returns text +language plpgsql stable as $$ +declare + v_item text; + v_norm text; + v_match text[]; + v_part text; + v_parts text[] := '{}'; +begin + if p_sort is null or btrim(p_sort) = '' then + return 'resource'; + end if; + foreach v_item in array string_to_array(p_sort, ',') loop + v_norm := lower(btrim(v_item)); + v_match := regexp_match(v_norm, '^([a-z_]+)(?:\s+(asc|desc))?(?:\s+nulls\s+(first|last))?$'); + if v_match is null or not exists ( + select 1 from billing.report_field + where id = v_match[1] and report_types @> array['finance'] + ) then + raise exception 'Invalid report expression.' using errcode = 'P0400'; + end if; + v_part := format('%I', v_match[1]); + if v_match[2] is not null then + v_part := v_part || ' ' || upper(v_match[2]); + end if; + if v_match[3] is not null then + v_part := v_part || ' NULLS ' || upper(v_match[3]); + end if; + v_parts := array_append(v_parts, v_part); + end loop; + return array_to_string(v_parts, ', '); +end; +$$; + create or replace function billing.finance_report( p_period text, p_fields text[], p_sort text, p_group_by text, p_filter text, p_having text ) returns jsonb @@ -16,6 +289,10 @@ declare v_select text; v_group text; v_values text; + v_filter_sql text; + v_group_sql text; + v_having_sql text; + v_sort_sql text; v_rows jsonb; begin if v_period !~ '^[0-9]{4}-(0[1-9]|1[0-2])$' or left(v_period, 4) = '0000' then @@ -30,6 +307,10 @@ begin )) then raise exception 'Unknown financial report column.' using errcode = 'P0400'; end if; + v_filter_sql := billing.sanitize_predicate(p_filter, 'filter'); + v_group_sql := billing.sanitize_group_by(p_group_by); + v_having_sql := billing.sanitize_predicate(p_having, 'having'); + v_sort_sql := billing.sanitize_sort(p_sort); select string_agg(format('%s as %I', expression, id), ', ' order by position, id) into v_context from billing.report_field where report_types @> array['finance'] and not aggregate; @@ -46,10 +327,10 @@ begin where to_char(r.created_at, ''YYYY-MM'') = $1 and (%s) group by %s having (%s) order by %s ) report', v_values, v_select, v_context, - coalesce(nullif(btrim(p_filter), ''), 'true'), - concat_ws(', ', coalesce(nullif(btrim(p_group_by), ''), 'period, resource, tariff'), v_group), - coalesce(nullif(btrim(p_having), ''), 'true'), - coalesce(nullif(btrim(p_sort), ''), 'resource') + v_filter_sql, + concat_ws(', ', v_group_sql, v_group), + v_having_sql, + v_sort_sql ) into v_rows using v_period; return jsonb_build_object('columns', v_columns, 'rows', v_rows); exception when syntax_error_or_access_rule_violation or data_exception then diff --git a/dark-tariff/backend/database/sql/schema/billing.sql b/dark-tariff/backend/database/sql/schema/billing.sql index 1324dea..a218894 100755 --- a/dark-tariff/backend/database/sql/schema/billing.sql +++ b/dark-tariff/backend/database/sql/schema/billing.sql @@ -12,9 +12,13 @@ create table if not exists billing.reading ( h bit varying[] not null, y bit varying not null, w integer not null, - parameters text not null + parameters text not null, + failed_checks integer not null default 0 ); +alter table billing.reading + add column if not exists failed_checks integer not null default 0; + create index if not exists reading_created_at_idx on billing.reading (created_at);