-
Notifications
You must be signed in to change notification settings - Fork 40
feat: redirect validation #1669
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
Merged
+267
−11
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
7d88592
fix: callback error message and code
emlimlf e1904a7
Merge branch 'main' into fix/callback-error-code
emlimlf 41847ce
fix: pr comments
emlimlf 9f785c8
feat: added valid redirect url check
emlimlf 0946ddc
feat: added error logging
emlimlf 9a6de0d
chore: address pr comments
emlimlf d0886d6
Merge branch 'main' into feat/redirect-validation
emlimlf 1b0944b
Merge branch 'main' into feat/redirect-validation
emlimlf e56dcfe
chore: address pr comments
emlimlf 293548c
Merge branch 'main' into feat/redirect-validation
emlimlf File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
16 changes: 16 additions & 0 deletions
16
database/migrations/V1770789662__createSecurityAuditLogsTable.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| -- Security audit logs for tracking security-related events | ||
| CREATE TABLE IF NOT EXISTS security_audit_logs ( | ||
| id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | ||
| created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, | ||
| event_type TEXT NOT NULL, | ||
| endpoint TEXT NOT NULL, | ||
| ip_address TEXT, | ||
| user_agent TEXT, | ||
| attempted_value TEXT, | ||
| details JSONB, | ||
| CONSTRAINT check_event_type CHECK (event_type IN ('invalid_redirect', 'auth_failure', 'rate_limit_exceeded')) | ||
| ); | ||
|
|
||
| -- Index for efficient querying by event type and time | ||
| CREATE INDEX idx_security_audit_logs_event_type ON security_audit_logs(event_type); | ||
| CREATE INDEX idx_security_audit_logs_created_at ON security_audit_logs(created_at); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| // Copyright (c) 2025 The Linux Foundation and each contributor. | ||
| // SPDX-License-Identifier: MIT | ||
| import type { Pool } from 'pg'; | ||
|
|
||
| export type SecurityAuditEventType = 'invalid_redirect' | 'auth_failure' | 'rate_limit_exceeded'; | ||
|
|
||
| export interface SecurityAuditLogEntry { | ||
| eventType: SecurityAuditEventType; | ||
| endpoint: string; | ||
| ipAddress?: string; | ||
| userAgent?: string; | ||
| attemptedValue?: string; | ||
| details?: Record<string, unknown>; | ||
| } | ||
|
|
||
| export class SecurityAuditRepository { | ||
| constructor(private pool: Pool) {} | ||
|
|
||
| /** | ||
| * Logs a security audit event to the database. | ||
| * This method is designed to be fire-and-forget - it catches and logs errors | ||
| * internally to avoid affecting the main request flow. | ||
| */ | ||
| async logSecurityEvent(entry: SecurityAuditLogEntry): Promise<void> { | ||
| try { | ||
| const query = ` | ||
| INSERT INTO security_audit_logs ( | ||
| event_type, | ||
| endpoint, | ||
| ip_address, | ||
| user_agent, | ||
| attempted_value, | ||
| details | ||
| ) | ||
| VALUES ($1, $2, $3, $4, $5, $6) | ||
| `; | ||
|
|
||
| await this.pool.query(query, [ | ||
| entry.eventType, | ||
| entry.endpoint, | ||
| entry.ipAddress || null, | ||
| entry.userAgent || null, | ||
| entry.attemptedValue || null, | ||
| entry.details ? JSON.stringify(entry.details) : null, | ||
| ]); | ||
| } catch (error) { | ||
| // Log to console but don't throw - security logging should not break the main flow | ||
| console.error('Failed to log security audit event:', error); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Logs an invalid redirect attempt. | ||
| * Convenience method for the common case of logging redirect validation failures. | ||
| */ | ||
| async logInvalidRedirect( | ||
| endpoint: string, | ||
| attemptedUrl: string, | ||
| ipAddress?: string, | ||
| userAgent?: string, | ||
| ): Promise<void> { | ||
| await this.logSecurityEvent({ | ||
| eventType: 'invalid_redirect', | ||
| endpoint, | ||
| ipAddress, | ||
| userAgent, | ||
| attemptedValue: attemptedUrl, | ||
| }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| // Copyright (c) 2025 The Linux Foundation and each contributor. | ||
| // SPDX-License-Identifier: MIT | ||
| import { isLocal } from './common'; | ||
|
|
||
| const ALLOWED_REDIRECT_DOMAINS = isLocal | ||
| ? ['linuxfoundation.org', 'auth0.com', 'localhost'] | ||
| : ['linuxfoundation.org', 'auth0.com']; | ||
| export const DEFAULT_REDIRECT = '/'; | ||
|
|
||
| /** | ||
| * Validates a redirect URL to prevent open redirect vulnerabilities. | ||
| * @param url - The URL to validate | ||
| * @returns true if the URL is safe for redirect, false otherwise | ||
| */ | ||
| export function isValidRedirectUrl(url: string | undefined | null): boolean { | ||
| // Reject empty/null/undefined | ||
| if (!url || typeof url !== 'string') { | ||
| return false; | ||
| } | ||
|
|
||
| const trimmedUrl = url.trim(); | ||
|
|
||
| if (!trimmedUrl) { | ||
| return false; | ||
| } | ||
|
|
||
| // Reject protocol-relative URLs (//example.com) - these bypass same-origin checks | ||
| if (trimmedUrl.startsWith('//')) { | ||
| return false; | ||
| } | ||
|
|
||
| // Reject javascript:, data:, vbscript:, and other dangerous protocols | ||
| const dangerousProtocols = ['javascript:', 'data:', 'vbscript:', 'file:']; | ||
| const lowerUrl = trimmedUrl.toLowerCase(); | ||
| if (dangerousProtocols.some((protocol) => lowerUrl.startsWith(protocol))) { | ||
| return false; | ||
| } | ||
|
|
||
| // Allow relative URLs (starting with / but not //) | ||
| if (trimmedUrl.startsWith('/') && !trimmedUrl.startsWith('//')) { | ||
| // Additional check: reject URLs with encoded characters that could bypass validation | ||
| // e.g., /%2F%2Fexample.com could decode to //example.com | ||
| try { | ||
| const decoded = decodeURIComponent(trimmedUrl); | ||
| if (decoded.startsWith('//')) { | ||
| return false; | ||
| } | ||
| } catch { | ||
| // If decoding fails, reject to be safe | ||
| return false; | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| // For absolute URLs, validate against allowed domains | ||
| try { | ||
| const parsedUrl = new URL(trimmedUrl); | ||
|
|
||
| if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') { | ||
| return false; | ||
| } | ||
|
|
||
| // Check if hostname matches or is a subdomain of allowed domains | ||
| const hostname = parsedUrl.hostname.toLowerCase(); | ||
| return ALLOWED_REDIRECT_DOMAINS.some((domain) => { | ||
| return hostname === domain || hostname.endsWith(`.${domain}`); | ||
| }); | ||
| } catch { | ||
| // If URL parsing fails, it's not a valid absolute URL | ||
| // Could be a malformed URL or a relative path without leading slash | ||
| // Reject to be safe | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Validates and sanitizes a redirect URL, returning a safe default if invalid. | ||
| * | ||
| * @param url - The URL to validate | ||
| * @param fallback - Optional custom fallback URL (defaults to "/") | ||
| * @returns The original URL if valid, otherwise the fallback | ||
| */ | ||
| export function getSafeRedirectUrl( | ||
| url: string | undefined | null, | ||
| fallback: string = DEFAULT_REDIRECT, | ||
| ): string { | ||
| if (isValidRedirectUrl(url)) { | ||
| return url!.trim(); | ||
| } | ||
| return fallback; | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.