Skip to content

Add option to rate limit the publish endpoint #1420

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
20 changes: 15 additions & 5 deletions package-lock.json

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

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
"getport": "^0.1.0",
"livereload": "^0.9.3",
"lodash.isequal": "^4.5.0",
"lru-cache": "^11.1.0",
"morgan": "^1.10.0",
"multer": "^1.4.3",
"nice-cache": "^0.0.5",
Expand Down Expand Up @@ -123,4 +124,4 @@
"universalify": "^2.0.0",
"yargs": "^17.7.2"
}
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { default as Client } from 'oc-client';
export { default as cli } from './cli/programmatic-api';
export { default as Registry, RegistryOptions } from './registry';
export { RateLimitStore } from './types';
60 changes: 60 additions & 0 deletions src/registry/domain/memory-rate-limit-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { LRUCache } from 'lru-cache';
import type { RateLimitStore } from '../../types';

interface RateLimitEntry {
hits: number;
resetTime: number;
}

export default class MemoryRateLimitStore implements RateLimitStore {
private store: LRUCache<string, RateLimitEntry>;

constructor(maxSize: number = 1000) {
this.store = new LRUCache({
max: maxSize,
// TTL is handled manually in our increment logic
ttl: 0,
// Don't allow stale items
allowStale: false,
// Update age on access to maintain LRU behavior
updateAgeOnGet: true,
// Clean up expired entries when they're accessed
dispose: (_value, _key) => {
// Optional: log when entries are disposed
}
});
}

async increment(
key: string,
windowMs: number
): Promise<{
totalHits: number;
resetTime: Date;
}> {
const now = Date.now();
const resetTime = new Date(now + windowMs);

const existing = this.store.get(key);

if (!existing || existing.resetTime < now) {
// New entry or expired entry
const entry: RateLimitEntry = {
hits: 1,
resetTime: now + windowMs
};
this.store.set(key, entry);
return {
totalHits: 1,
resetTime
};
}

// Increment existing entry
existing.hits++;
return {
totalHits: existing.hits,
resetTime: new Date(existing.resetTime)
};
}
}
68 changes: 68 additions & 0 deletions src/registry/middleware/publish-rate-limit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import type { NextFunction, Request, Response } from 'express';
import type { Config, RateLimitStore } from '../../types';
import MemoryRateLimitStore from '../domain/memory-rate-limit-store';

const DEFAULT_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
const DEFAULT_MAX_HITS = 100;
const DEFAULT_MAX_CACHE_SIZE = 1000; // Maximum number of rate limit entries to keep in memory

function defaultKeyGenerator(req: Request): string {
return `${req.ip}:${req.user ?? 'anon'}`;
}

export default function createPublishRateLimiter(conf: Config) {
const rateLimitConfig = conf.publishRateLimit ?? {};
Copy link
Collaborator

Choose a reason for hiding this comment

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

rather than gathering things like windowMs, maxHits, maxCacheSize, etc. on global level wouldn't it be better to leave it purely to the rate limit store?

So you could provide in config a factory function that would provide those values to the store directly. For default store you would provide those values on line 22, but not configurable.

const windowMs = rateLimitConfig.windowMs ?? DEFAULT_WINDOW_MS;
const maxHits = rateLimitConfig.max ?? DEFAULT_MAX_HITS;
const keyGenerator = rateLimitConfig.keyGenerator ?? defaultKeyGenerator;
const skip = rateLimitConfig.skip;
const maxCacheSize = rateLimitConfig.maxCacheSize ?? DEFAULT_MAX_CACHE_SIZE;

// Use provided store or create memory store with configurable size
const store: RateLimitStore =
rateLimitConfig.store ?? new MemoryRateLimitStore(maxCacheSize);

// Initialize store if it has an init method
if (store.init) {
store.init();
}

return async function publishRateLimiter(
req: Request,
res: Response,
next: NextFunction
): Promise<void> {
try {
// Skip rate limiting if skip function returns true
if (skip?.(req)) {
return next();
}

const key = keyGenerator(req);
const { totalHits, resetTime } = await store.increment(key, windowMs);

if (totalHits > maxHits) {
// Calculate seconds until reset
const retryAfter = Math.ceil((resetTime.getTime() - Date.now()) / 1000);

res.set('Retry-After', retryAfter.toString());

res.status(429).json({
error: 'rate_limit_exceeded',
message: 'Too many publish requests',
resetTime: resetTime.toISOString(),
retryAfter
});

// Set Retry-After header
return;
}

next();
} catch (error) {
// If rate limiting fails, log error but allow request to proceed
console.error('Rate limiting error:', error);
next();
}
};
}
3 changes: 3 additions & 0 deletions src/registry/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Express } from 'express';
import type { Repository } from '../registry/domain/repository';
import settings from '../resources/settings';
import type { Config } from '../types';
import createPublishRateLimiter from './middleware/publish-rate-limit';
import IndexRoute from './routes';
import ComponentRoute from './routes/component';
import ComponentInfoRoute from './routes/component-info';
Expand All @@ -28,6 +29,7 @@ export function create(app: Express, conf: Config, repository: Repository) {
};

const prefix = conf.prefix;
const publishRateLimiter = createPublishRateLimiter(conf);

if (prefix !== '/') {
app.get('/', (_req, res) => res.redirect(prefix));
Expand All @@ -50,6 +52,7 @@ export function create(app: Express, conf: Config, repository: Repository) {
} else {
app.put(
`${prefix}:componentName/:componentVersion`,
publishRateLimiter,
conf.beforePublish,
routes.publish
);
Expand Down
58 changes: 58 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,10 @@ export interface Config<T = any> {
* @default 0
*/
verbosity: number;
/**
* Rate limiting configuration for component publishing.
*/
publishRateLimit?: PublishRateLimit;
}

type CompiledTemplate = (model: unknown) => string;
Expand Down Expand Up @@ -402,6 +406,60 @@ export interface Plugin<T = any> {
};
}

interface IncrementResult {
totalHits: number;
resetTime: Date;
}

export interface RateLimitStore {
/** Called once on registry start-up (optional) */
init?: () => Promise<void> | void;

/**
* Atomically increase the counter for the key.
* Returns the current hit count and the absolute reset time.
*/
increment: (
key: string,
windowMs: number
) => Promise<IncrementResult> | IncrementResult;
}

export interface PublishRateLimit {
/**
* Size of the sliding window in **ms** (default 15 min)
*
* @default 15 * 60 * 1000
*/
windowMs?: number;
/**
* Maximum hits allowed within `windowMs` (default 100)
*
* @default 100
*/
max?: number;
/**
* Custom key generator.
*
* Defaults to: `${req.ip}:${req.user ?? 'anon'}`
*/
keyGenerator?: (req: Request) => string;
/**
* Skip throttling for specific requests/users
*/
skip?: (req: Request) => boolean;
/**
* Custom storage backend. Defaults to in-memory Map.
*/
store?: RateLimitStore;
/**
* Maximum number of rate limit entries to keep in memory (default 1000)
*
* @default 1000
*/
maxCacheSize?: number;
}

declare global {
namespace Express {
interface Request {
Expand Down