Chore: harden SafeUrlPipe

This commit is contained in:
shamoon
2025-12-18 06:30:58 -08:00
parent d8397ac77e
commit 84c59f45da
2 changed files with 49 additions and 11 deletions

View File

@@ -13,20 +13,45 @@ describe('SafeUrlPipe', () => {
pipe = TestBed.inject(SafeUrlPipe)
})
it('should bypass security and trust the url', () => {
const url = 'https://example.com'
it('should trust only same-origin http/https urls', () => {
const origin = window.location.origin
const url = `${origin}/some/path`
const domSanitizer = TestBed.inject(DomSanitizer)
const sanitizerSpy = jest.spyOn(
domSanitizer,
'bypassSecurityTrustResourceUrl'
)
let safeResourceUrl = pipe.transform(url)
const safeResourceUrl = pipe.transform(url)
expect(safeResourceUrl).not.toBeNull()
expect(sanitizerSpy).toHaveBeenCalled()
expect(sanitizerSpy).toHaveBeenCalledWith(url)
})
safeResourceUrl = pipe.transform(null)
expect(safeResourceUrl).not.toBeNull()
expect(sanitizerSpy).toHaveBeenCalled()
it('should return null for null or unsafe urls', () => {
const sanitizerSpy = jest.spyOn(
TestBed.inject(DomSanitizer),
'bypassSecurityTrustResourceUrl'
)
expect(pipe.transform(null)).toBeTruthy()
expect(sanitizerSpy).toHaveBeenCalledWith('')
expect(pipe.transform('javascript:alert(1)')).toBeTruthy()
expect(sanitizerSpy).toHaveBeenCalledWith('')
const otherOrigin =
window.location.origin === 'https://example.com'
? 'https://evil.com'
: 'https://example.com'
expect(pipe.transform(`${otherOrigin}/file`)).toBeTruthy()
expect(sanitizerSpy).toHaveBeenCalledWith('')
})
it('should return null for malformed urls', () => {
const sanitizerSpy = jest.spyOn(
TestBed.inject(DomSanitizer),
'bypassSecurityTrustResourceUrl'
)
expect(pipe.transform('http://[invalid-url')).toBeTruthy()
expect(sanitizerSpy).toHaveBeenCalledWith('')
})
})