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
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ describe('AuthService Refresh Token Reuse', () => {
});

it('should detect reuse and invalidate sessions', async () => {
(jwt.verify as jest.Mock).mockReturnValue({ sessionId: 'session-1', sub: 'user-1' });
(jwt.verify as jest.Mock).mockReturnValue({
sessionId: 'session-1',
sub: 'user-1',
});

(prisma.session.findUnique as jest.Mock).mockResolvedValue({
id: 'session-1',
Expand Down Expand Up @@ -97,7 +100,10 @@ describe('AuthService Refresh Token Reuse', () => {
});

it('should lock session after 5 failed attempts', async () => {
(jwt.verify as jest.Mock).mockReturnValue({ sessionId: 'session-1', sub: 'user-1' });
(jwt.verify as jest.Mock).mockReturnValue({
sessionId: 'session-1',
sub: 'user-1',
});

(prisma.session.findUnique as jest.Mock).mockResolvedValue({
id: 'session-1',
Expand Down Expand Up @@ -127,7 +133,10 @@ describe('AuthService Refresh Token Reuse', () => {
});

it('should reject locked sessions', async () => {
(jwt.verify as jest.Mock).mockReturnValue({ sessionId: 'session-1', sub: 'user-1' });
(jwt.verify as jest.Mock).mockReturnValue({
sessionId: 'session-1',
sub: 'user-1',
});

(prisma.session.findUnique as jest.Mock).mockResolvedValue({
id: 'session-1',
Expand All @@ -140,4 +149,4 @@ describe('AuthService Refresh Token Reuse', () => {
service.refresh({ refreshToken: 'any-token' }),
).rejects.toThrow(SessionLockedError);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,12 @@ export const configSchema = Joi.object({
HORIZON_URL: Joi.string().uri().allow(''),
SOROBAN_RPC_URL: Joi.string().uri().allow(''),
// Signing (#542): explicit mode — never treat missing secret as silent simulate
STELLAR_SIGNING_MODE: Joi.string().valid('simulate', 'live').default('simulate'),
STELLAR_SIGNING_PROVIDER: Joi.string().valid('env', 'kms', 'vault').default('env'),
STELLAR_SIGNING_MODE: Joi.string()
.valid('simulate', 'live')
.default('simulate'),
STELLAR_SIGNING_PROVIDER: Joi.string()
.valid('env', 'kms', 'vault')
.default('env'),
STELLAR_SECRET_KEY: Joi.string().allow('', null),
STELLAR_TRANSFER_SECRET_KEY: Joi.string().allow('', null),
STELLAR_KMS_KEY_ID: Joi.string().allow('', null),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,15 @@ export class IpfsController {
}

@Get('documents')
async listDocuments(@CurrentUser() user: JwtPayload) {
return this.upload.listDocuments(user.companyId);
async listDocuments(
@CurrentUser() user: JwtPayload,
@Query('page') page?: string,
@Query('limit') limit?: string,
) {
return this.upload.listDocuments(user.companyId, {
page: page ? parseInt(page, 10) : undefined,
limit: limit ? parseInt(limit, 10) : undefined,
});
}

@Get('documents/:referenceId')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,9 +207,20 @@ export class UploadService {
);
}

async listDocuments(companyId?: string) {
async listDocuments(
companyId?: string,
pagination?: { page?: number; limit?: number },
) {
const take = pagination?.limit;
const skip =
pagination?.page && pagination?.limit
? (pagination.page - 1) * pagination.limit
: undefined;

return this.prisma.ipfsDocument.findMany({
where: companyId ? { companyId } : {},
...(skip !== undefined ? { skip } : {}),
...(take !== undefined ? { take } : {}),
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,7 @@ export class ProgressTrackingService {
const base = Number(target.baseYearEmissions);
const reduction = Number(target.reductionPercentage) / 100;
const span = Math.max(1, target.targetYear - target.baseYear);
const progress = Math.min(
1,
Math.max(0, (year - target.baseYear) / span),
);
const progress = Math.min(1, Math.max(0, (year - target.baseYear) / span));
const targetAtEnd = base * (1 - reduction);
return base + (targetAtEnd - base) * progress;
}
Expand All @@ -87,10 +84,7 @@ export class ProgressTrackingService {
const requiredCut = base * reduction;
if (requiredCut <= 0) return 0;
const actualCut = base - latestActual;
return Math.max(
0,
Math.min(100, (actualCut / requiredCut) * 100),
);
return Math.max(0, Math.min(100, (actualCut / requiredCut) * 100));
}

classifyTrackStatus(
Expand Down Expand Up @@ -124,8 +118,7 @@ export class ProgressTrackingService {
}
return years.map((year) => ({
year,
actualEmissions:
byYear.get(year) ?? Number(target.baseYearEmissions),
actualEmissions: byYear.get(year) ?? Number(target.baseYearEmissions),
targetEmissions: this.expectedEmissionsAtYear(target, year),
}));
}
Expand All @@ -144,9 +137,7 @@ export class ProgressTrackingService {
const targetEntries: TargetDashboardEntry[] = targets.map((t) => {
const rows = progressRows.filter((p) => p.targetId === t.id);
const series = this.buildSeries(t, rows);
const latest = series.length
? series[series.length - 1]
: null;
const latest = series.length ? series[series.length - 1] : null;
const latestEmissions = latest ? latest.actualEmissions : null;
const latestYear = latest ? latest.year : t.baseYear;
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ describe('EnvSigningProvider (#542)', () => {
it('signTransaction rejects in simulate mode', async () => {
process.env.STELLAR_SIGNING_MODE = 'simulate';
const p = new EnvSigningProvider('transfer');
await expect(p.signTransaction('AAAA', 'Test SDF Network ; September 2015')).rejects.toThrow(
/simulate mode/i,
);
await expect(
p.signTransaction('AAAA', 'Test SDF Network ; September 2015'),
).rejects.toThrow(/simulate mode/i);
});

it('KmsSigningProvider fails closed when selected without public key', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ export class KmsSigningProvider implements SigningProvider, OnModuleInit {

onModuleInit(): void {
if (!this.enabled) {
this.logger.debug(`KmsSigningProvider not selected (category=${this.category})`);
this.logger.debug(
`KmsSigningProvider not selected (category=${this.category})`,
);
return;
}
if (!this.publicKey) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ export interface SigningProvider {
* Sign a prepared transaction XDR string.
* Implementations must not retain secret material longer than needed.
*/
signTransaction(txXdr: string, networkPassphrase: string): Promise<SignedPayload>;
signTransaction(
txXdr: string,
networkPassphrase: string,
): Promise<SignedPayload>;

/** True when this provider produces real on-chain signatures */
isLive(): boolean;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ import { ConfigModule } from '../../config/config.module';
import { SigningModule } from '../signing/signing.module';

@Module({
imports: [OwnershipHistoryModule, IdempotencyModule, ConfigModule, SigningModule],
imports: [
OwnershipHistoryModule,
IdempotencyModule,
ConfigModule,
SigningModule,
],
providers: [
SorobanService,
CarbonAssetService,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { IsArray, IsBoolean, IsNotEmpty, IsNumber, IsString, ValidateNested } from 'class-validator';
import {
IsArray,
IsBoolean,
IsNotEmpty,
IsNumber,
IsString,
ValidateNested,
} from 'class-validator';
import { Type } from 'class-transformer';

class SorobanEventValueDto {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { createHmac, timingSafeEqual } from 'crypto';
import { Request } from 'express';
import { SecurityEvents } from '../../security/constants/security-events.constants';
Expand All @@ -8,7 +13,10 @@ type RawRequest = Request & { rawBody?: Buffer };

@Injectable()
export class WebhookSignatureGuard implements CanActivate {
private readonly requests = new Map<string, { started: number; count: number }>();
private readonly requests = new Map<
string,
{ started: number; count: number }
>();

constructor(private readonly security: SecurityService) {}

Expand All @@ -17,26 +25,44 @@ export class WebhookSignatureGuard implements CanActivate {
const ip = request.ip || 'unknown';
const now = Date.now();
const bucket = this.requests.get(ip);
if (!bucket || now - bucket.started >= 60_000) this.requests.set(ip, { started: now, count: 1 });
if (!bucket || now - bucket.started >= 60_000)
this.requests.set(ip, { started: now, count: 1 });
else if (++bucket.count > 100) await this.reject(request, 'rate-limit');

const secret = process.env.WEBHOOK_SIGNING_SECRET;
const timestamp = request.header('X-Webhook-Timestamp');
const supplied = request.header('X-Webhook-Signature')?.replace(/^sha256=/i, '') ?? '';
const supplied =
request.header('X-Webhook-Signature')?.replace(/^sha256=/i, '') ?? '';
const rawBody = request.rawBody;
const timestampMs = timestamp ? Number(timestamp) * 1000 : NaN;
const fresh = Number.isFinite(timestampMs) && Math.abs(now - timestampMs) <= 5 * 60_000;
const payload = rawBody && timestamp ? `${timestamp}.${rawBody.toString('utf8')}` : '';
const expected = secret && payload ? createHmac('sha256', secret).update(payload).digest('hex') : '';
const valid = Boolean(expected && supplied.length === expected.length && timingSafeEqual(Buffer.from(supplied), Buffer.from(expected)));
if (!secret || !rawBody || !valid || !fresh) await this.reject(request, !fresh ? 'stale-timestamp' : 'invalid-signature');
const fresh =
Number.isFinite(timestampMs) && Math.abs(now - timestampMs) <= 5 * 60_000;
const payload =
rawBody && timestamp ? `${timestamp}.${rawBody.toString('utf8')}` : '';
const expected =
secret && payload
? createHmac('sha256', secret).update(payload).digest('hex')
: '';
const valid = Boolean(
expected &&
supplied.length === expected.length &&
timingSafeEqual(Buffer.from(supplied), Buffer.from(expected)),
);
if (!secret || !rawBody || !valid || !fresh)
await this.reject(
request,
!fresh ? 'stale-timestamp' : 'invalid-signature',
);
return true;
}

private async reject(request: RawRequest, reason: string): Promise<never> {
await this.security.logEvent({
eventType: SecurityEvents.SuspiciousPatternDetected,
companyId: typeof request.body?.companyId === 'string' ? request.body.companyId : null,
companyId:
typeof request.body?.companyId === 'string'
? request.body.companyId
: null,
ipAddress: request.ip,
method: request.method,
resource: request.originalUrl,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { ConflictException, Injectable, Logger, NotFoundException } from '@nestjs/common';
import {
ConflictException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { PrismaService } from '../../shared/database/prisma.service';
import {
StellarWebhookDto,
Expand All @@ -22,7 +27,9 @@ export class StellarWebhookService {
select: { companyId: true },
});
if (existing && existing.companyId !== dto.companyId) {
throw new ConflictException('Transaction confirmation belongs to another company');
throw new ConflictException(
'Transaction confirmation belongs to another company',
);
}

return this.prisma.transactionConfirmation.upsert({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('Auction API Integration Tests', () => {
let app: INestApplication;
const mockCompanyId = 'test-company-id-1';
const mockAuthToken = 'valid-jwt-token';

const mockPrismaService = new Proxy({} as any, {
get: (target, prop) => {
if (typeof prop === 'string' && !target[prop]) {
Expand Down Expand Up @@ -78,15 +78,11 @@ describe('Auction API Integration Tests', () => {

describe('Unauthenticated Requests', () => {
it('should return 401 for GET /api/v1/auctions', async () => {
await request(app.getHttpServer())
.get('/api/v1/auctions')
.expect(401);
await request(app.getHttpServer()).get('/api/v1/auctions').expect(401);
});

it('should return 401 for GET /api/v1/auctions/:id', async () => {
await request(app.getHttpServer())
.get('/api/v1/auctions/1')
.expect(401);
await request(app.getHttpServer()).get('/api/v1/auctions/1').expect(401);
});

it('should return 401 for POST /api/v1/auctions', async () => {
Expand Down Expand Up @@ -125,7 +121,7 @@ describe('Auction API Integration Tests', () => {
describe('Authenticated Requests', () => {
it('should allow GET /api/v1/auctions when authenticated', async () => {
mockPrismaService.findMany = jest.fn().mockResolvedValue([]);

await request(app.getHttpServer())
.get('/api/v1/auctions')
.set('Authorization', `Bearer ${mockAuthToken}`)
Expand Down
28 changes: 28 additions & 0 deletions corporate-platform/corporate-platform-web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading