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
7 changes: 7 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,13 @@ jobs:
$wheels = @(Get-ChildItem artifacts\python-x64\payload -Filter *.whl -File)
if ($wheels.Count -ne 1) { throw 'Expected exactly the verified CPython 3.12 x64 wheel' }
& $python -m pip install $wheels[0].FullName --no-deps --no-index --quiet
- name: Check prebuilt Python native imports
shell: pwsh
run: |
$PSNativeCommandUseErrorActionPreference = $true
$native = @(Get-ChildItem bindings\py\.venv\Lib\site-packages\dynwinrt -Filter *.pyd -File)
if ($native.Count -ne 1) { throw 'Expected exactly one installed production Python extension' }
node bindings\js\scripts\check-ui-helper-imports.mjs $native[0].FullName
- name: Test Python binding
run: |
.\bindings\py\.venv\Scripts\python.exe -m pytest bindings\py\tests -q
Expand Down
8 changes: 8 additions & 0 deletions .github/workflows/python-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ on:
- 'bindings/py/**'
- 'crates/dynwinrt/**'
- 'crates/dynwinrt-com-contracts/**'
- 'bindings/js/scripts/pe-imports.mjs'
- 'bindings/js/scripts/check-ui-helper-imports.mjs'
- 'eng/release/python/prepare_python_release.py'
- 'eng/release/python/test_python_*_wheel.ps1'
- 'eng/release/python/verify_python_release.py'
Expand Down Expand Up @@ -334,6 +336,9 @@ jobs:
with:
name: python-runtime-${{ matrix.tag }}-x64
path: artifacts\runtime
- uses: actions/setup-node@v4
with:
node-version: 24
- uses: actions/download-artifact@v4
with:
name: python-codegen-x64
Expand Down Expand Up @@ -370,6 +375,9 @@ jobs:
with:
name: python-runtime-${{ matrix.tag }}-arm64
path: artifacts\runtime
- uses: actions/setup-node@v4
with:
node-version: 24
- uses: actions/download-artifact@v4
with:
name: python-codegen-arm64
Expand Down
6 changes: 5 additions & 1 deletion bindings/js/__test__/native-imports.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import test from 'ava'
import { spawnSync, type SpawnSyncReturns } from 'node:child_process'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { verifyDispatcherQueueImports } from '../scripts/pe-imports.mjs'
import { verifyDispatcherQueueImports, verifyUiHelperImports } from '../scripts/pe-imports.mjs'

const packageDir = fileURLToPath(new URL('..', import.meta.url))
const distDir = join(packageDir, 'dist')
Expand Down Expand Up @@ -35,6 +35,10 @@ test('native addons do not statically import CoreMessaging or CreateDispatcherQu
t.true(verifyDispatcherQueueImports(distDir).length > 0)
})

test('production native addons have no ordinary or delay GDI/USER32 helper imports', (t) => {
t.true(verifyUiHelperImports(distDir).length > 0)
})

for (const entrypoint of ['@microsoft/dynwinrt', '@microsoft/dynwinrt/com']) {
test(`fresh ${entrypoint} import does not load CoreMessaging for DispatcherQueue`, (t) => {
const child = spawnSync(
Expand Down
129 changes: 129 additions & 0 deletions bindings/js/__test__/pe-imports.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@
// Licensed under the MIT License.

import test from 'ava'
import { spawnSync } from 'node:child_process'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
assertNoDispatcherQueueImports,
assertNoEagerWin32Imports,
assertNoUiHelperImports,
readPeImports,
verifyAddonImports,
verifyDispatcherQueueImports,
verifyUiHelperImports,
} from '../scripts/pe-imports.mjs'

function fixture(wide: boolean) {
Expand Down Expand Up @@ -510,3 +513,129 @@ test('Win32 DispatcherQueue verification scans every addon including ARM64 delay
rmSync(directory, { recursive: true, force: true })
}
})

test('UI helper policy rejects DLL descriptors and scoped exports without banning OLEAUT32', (t) => {
for (const dll of ['GDI32.dll', 'user32.dll', 'C:\\Windows\\System32\\UsEr32.DlL']) {
for (const symbols of [['UnrelatedExport'], [17], []]) {
t.throws(() => assertNoUiHelperImports([{ dll, symbols }]), { message: /GDI\/USER32.*dynamically/ })
}
}
for (const symbol of [
'DeleteObject',
'DestroyIcon',
'CreateWindowExW',
'AreDpiAwarenessContextsEqual',
'GetDpiAwarenessContextForProcess',
'SetProcessDpiAwarenessContext',
'SetThreadDpiAwarenessContext',
]) {
for (const spelling of [symbol, symbol.toLowerCase(), `_${symbol}@8`, `__imp_${symbol}`]) {
t.throws(() => assertNoUiHelperImports([{ dll: 'api-alias.dll', symbols: [spelling] }]), {
message: /api-alias\.dll:/,
})
}
}
t.notThrows(() =>
assertNoUiHelperImports([
{ dll: 'kernel32.dll', symbols: ['LoadLibraryExW', 'GetProcAddress'] },
{ dll: 'oleaut32.dll', symbols: ['SysAllocStringLen', 'VariantClear', 'SafeArrayDestroy'] },
{ dll: 'ole32.dll', symbols: ['CoInitializeEx'] },
{ dll: 'combase.dll', symbols: ['RoInitialize'] },
]),
)
})

for (const wide of [false, true]) {
for (const delayed of [false, true]) {
test(`UI helper policy inspects ${wide ? 'PE32+' : 'PE32'} ${delayed ? 'delay' : 'ordinary'} tables`, (t) => {
const { bytes, writeThunk, width } = delayFixture(wide)
// Start with unrelated DLLs in both directories.
bytes.write('other.dll\0', 0x450)
const name = delayed ? 0x490 : 0x760
const symbol = delayed ? 0x522 : 0x782
const lookup = delayed ? 0x3a0 : 0x2a0
const options = { includeDelayImports: true }
t.notThrows(() => assertNoUiHelperImports(readPeImports(bytes, options)))
bytes.write('gdi32.dll\0', name)
writeThunk(lookup, (1n << BigInt(width * 8 - 1)) | 17n)
t.throws(() => assertNoUiHelperImports(readPeImports(bytes, options)), { message: /gdi32\.dll: #17/ })
bytes.write('alias.dll\0', name)
writeThunk(lookup, BigInt(delayed ? 0x2320 : 0x4080))
bytes.write('_SetThreadDpiAwarenessContext@4\0', symbol)
t.throws(() => assertNoUiHelperImports(readPeImports(bytes, options)), { message: /alias\.dll: _SetThread/ })
})
}
}

test('UI helper production checks scan every architecture and Python extensions without loading them', (t) => {
const directory = mkdtempSync(fileURLToPath(new URL('../target-pe-imports-', import.meta.url)))
const safe = fixture(true)
safe.bytes.write('ole32.dll\0', 0x760)
const forbidden = delayFixture(true)
forbidden.bytes.writeUInt16LE(0xaa64, 0x84)
const x64 = 'dynwinrt.win32-x64-msvc.node'
const arm64 = 'dynwinrt.win32-arm64-msvc.node'
const script = fileURLToPath(new URL('../scripts/check-ui-helper-imports.mjs', import.meta.url))
const pyd = join(directory, 'dynwinrt.cp313-win_arm64.pyd')
try {
t.throws(() => verifyUiHelperImports(directory), { message: /No native addons/ })
writeFileSync(join(directory, x64), safe.bytes)
writeFileSync(join(directory, arm64), forbidden.bytes)
t.throws(() => verifyUiHelperImports(directory), { message: /arm64-msvc\.node:.*GDI\/USER32/ })
writeFileSync(join(directory, arm64), safe.bytes)
t.deepEqual(verifyUiHelperImports(directory), [arm64, x64])
writeFileSync(pyd, safe.bytes)
t.is(spawnSync(process.execPath, [script, pyd], { encoding: 'utf8' }).status, 0)
writeFileSync(pyd, forbidden.bytes)
const child = spawnSync(process.execPath, [script, pyd], { encoding: 'utf8' })
t.not(child.status, 0)
t.regex(child.stderr, /GDI\/USER32/)
writeFileSync(join(directory, arm64), Buffer.from('MZ'))
t.throws(() => verifyUiHelperImports(directory), { message: /arm64-msvc\.node: Invalid PE import table/ })
} finally {
rmSync(directory, { recursive: true, force: true })
}
})

test('UI helper CLI permits optional Win32 delay-only imports but still rejects their ordinary imports', (t) => {
const directory = mkdtempSync(fileURLToPath(new URL('../target-pe-imports-', import.meta.url)))
const script = fileURLToPath(new URL('../scripts/check-ui-helper-imports.mjs', import.meta.url))
const pyd = join(directory, 'optional-subsystem.pyd')
try {
for (const wide of [false, true]) {
for (const [dll, symbol] of [
['mapi32.dll', 'MAPIInitialize'],
['gdiplus.dll', 'GdiplusStartup'],
['ws2_32.dll', 'WSAStartup'],
['mfplat.dll', 'MFStartup'],
]) {
const delayed = delayFixture(wide)
delayed.bytes.writeUInt32LE(0, delayed.directory + 8)
delayed.bytes.writeUInt32LE(0, delayed.directory + 12)
delayed.bytes.fill(0, 0x340, 0x360)
delayed.bytes.write(`${dll}\0`, 0x450)
delayed.bytes.write(`${symbol}\0`, 0x4d2)
const ordinary = readPeImports(delayed.bytes)
const combined = readPeImports(delayed.bytes, { includeDelayImports: true })
t.deepEqual(ordinary, [])
t.deepEqual(combined, [{ dll, symbols: [symbol, 23] }])
t.notThrows(() => assertNoEagerWin32Imports(ordinary))
t.notThrows(() => assertNoUiHelperImports(combined))
t.notThrows(() => assertNoDispatcherQueueImports(combined))
writeFileSync(pyd, delayed.bytes)
const accepted = spawnSync(process.execPath, [script, pyd], { encoding: 'utf8' })
t.is(accepted.status, 0, accepted.stderr)

const eager = fixture(wide)
eager.bytes.write(`${dll}\0`, 0x760)
eager.bytes.write(`${symbol}\0`, 0x782)
writeFileSync(pyd, eager.bytes)
const rejected = spawnSync(process.execPath, [script, pyd], { encoding: 'utf8' })
t.not(rejected.status, 0)
t.regex(rejected.stderr, /Optional Win32 subsystem DLLs must load lazily/)
}
}
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
27 changes: 27 additions & 0 deletions bindings/js/scripts/check-ui-helper-imports.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import { readFileSync } from 'node:fs'
import { extname } from 'node:path'
import {
assertNoDispatcherQueueImports,
assertNoEagerWin32Imports,
assertNoUiHelperImports,
readPeImports,
} from './pe-imports.mjs'

const files = process.argv.slice(2)
if (!files.length) throw new Error('Usage: node check-ui-helper-imports.mjs <production.node|production.pyd> [...]')
for (const file of files) {
if (!['.node', '.pyd'].includes(extname(file).toLowerCase())) {
throw new Error(`Expected a production .node or .pyd binary: ${file}`)
}
const bytes = readFileSync(file)
const ordinary = readPeImports(bytes)
const combined = readPeImports(bytes, { includeDelayImports: true })
assertNoUiHelperImports(combined)
assertNoDispatcherQueueImports(combined)
// The existing optional-subsystem policy permits delay imports.
assertNoEagerWin32Imports(ordinary)
console.log(`Verified production native import policies: ${file}`)
}
2 changes: 2 additions & 0 deletions bindings/js/scripts/pe-imports.d.mts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@ export interface PeImport {
export function readPeImports(bytes: Buffer, options?: { includeDelayImports?: boolean }): PeImport[]
export function assertNoEagerWin32Imports(imports: PeImport[], options?: { testHooks?: boolean }): void
export function assertNoDispatcherQueueImports(imports: PeImport[]): void
export function assertNoUiHelperImports(imports: PeImport[]): void
export function verifyAddonImports(directory: string, options?: { testHooksAddon?: string }): string[]
export function verifyDispatcherQueueImports(directory: string): string[]
export function verifyUiHelperImports(directory: string): string[]
49 changes: 49 additions & 0 deletions bindings/js/scripts/pe-imports.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,48 @@ export function assertNoDispatcherQueueImports(imports) {
}
}

const uiHelperSymbols = new Set([
'deleteobject',
'destroyicon',
'createwindowexw',
'aredpiawarenesscontextsequal',
'getdpiawarenesscontextforprocess',
'setprocessdpiawarenesscontext',
'setthreaddpiawarenesscontext',
])

/**
* Production binaries must resolve the scoped GDI/USER32 helpers dynamically.
* This is a direct-import guarantee, not an OS/host transitive DLL-load guarantee.
* @param {PeImport[]} imports
*/
export function assertNoUiHelperImports(imports) {
const violations = imports.filter(
({ dll, symbols }) =>
['gdi32.dll', 'user32.dll'].includes(win32.basename(dll).toLowerCase()) ||
symbols.some(
(symbol) =>
typeof symbol === 'string' &&
uiHelperSymbols.has(
symbol
.toLowerCase()
.replace(/^(__imp_)?_?/, '')
.replace(/@\d+$/, ''),
),
),
)
if (violations.length) {
throw new Error(
`Production GDI/USER32 helpers must resolve dynamically; PE imports:\n${violations
.map(
({ dll, symbols }) =>
`${dll}: ${symbols.map((symbol) => (typeof symbol === 'number' ? `#${symbol}` : symbol)).join(', ')}`,
)
.join('\n')}`,
)
}
}

/**
* @param {string} directory
* @param {(bytes: Buffer, addon: string) => void} inspect
Expand Down Expand Up @@ -244,3 +286,10 @@ export function verifyDispatcherQueueImports(directory) {
assertNoDispatcherQueueImports(readPeImports(bytes, { includeDelayImports: true })),
)
}

/** @param {string} directory */
export function verifyUiHelperImports(directory) {
return verifyAddonFiles(directory, (bytes) =>
assertNoUiHelperImports(readPeImports(bytes, { includeDelayImports: true })),
)
}
3 changes: 2 additions & 1 deletion bindings/js/scripts/verify-runtime-artifact.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { readFileSync, realpathSync, statSync } from 'node:fs'
import { createRequire } from 'node:module'
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { verifyAddonImports } from './pe-imports.mjs'
import { verifyAddonImports, verifyUiHelperImports } from './pe-imports.mjs'

const args = process.argv.slice(2)
if (args.length !== 1 && !(args.length === 2 && args[1] === '--test-hooks')) {
Expand All @@ -20,6 +20,7 @@ const require = createRequire(join(artifact, 'artifact-consumer.cjs'))
const modules = new Map()
const testHooksAddon = args[1] === '--test-hooks' ? `dynwinrt.win32-${process.arch}-msvc.node` : undefined
const addons = verifyAddonImports(artifact, { testHooksAddon })
if (!testHooksAddon) verifyUiHelperImports(artifact)
if (testHooksAddon) {
assert.equal(
typeof require(join(artifact, testHooksAddon)).DynComBorrowedCopyTestFixture,
Expand Down
15 changes: 9 additions & 6 deletions bindings/js/src/com.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ pub(crate) fn apartment_bound_com_object(value: IUnknown) -> napi::Result<DynWin

fn create_test_hwnd() -> napi::Result<BigInt> {
use std::sync::atomic::{AtomicUsize, Ordering};
use windows::Win32::UI::WindowsAndMessaging::{CreateWindowExW, WINDOW_EX_STYLE, WS_POPUP};
use windows::Win32::UI::WindowsAndMessaging::{WINDOW_EX_STYLE, WS_POPUP};

static CACHED_HWND: AtomicUsize = AtomicUsize::new(0);
let cached = CACHED_HWND.load(Ordering::Acquire);
Expand All @@ -324,7 +324,7 @@ fn create_test_hwnd() -> napi::Result<BigInt> {
let class_name: Vec<u16> = "STATIC".encode_utf16().chain(Some(0)).collect();
let title: Vec<u16> = "dynwinrt-test-hwnd\0".encode_utf16().collect();
let hwnd = unsafe {
CreateWindowExW(
dynwinrt::system_helpers::create_window_ex(
WINDOW_EX_STYLE(0),
windows::core::PCWSTR(class_name.as_ptr()),
windows::core::PCWSTR(title.as_ptr()),
Expand Down Expand Up @@ -2972,10 +2972,11 @@ impl DynComOwnedHandle {
let succeeded = match cleanup {
dynwinrt::com::OwnedHandleCleanup::DeleteObject if force_failure => false,
dynwinrt::com::OwnedHandleCleanup::DeleteObject => unsafe {
windows::Win32::Graphics::Gdi::DeleteObject(windows::Win32::Graphics::Gdi::HGDIOBJ(
std::ptr::with_exposed_provenance_mut(address),
))
.as_bool()
dynwinrt::system_helpers::GdiObjectDeleter::prepared()
.delete(windows::Win32::Graphics::Gdi::HGDIOBJ(
std::ptr::with_exposed_provenance_mut(address),
))
.as_bool()
},
};
if succeeded {
Expand Down Expand Up @@ -6602,6 +6603,7 @@ mod tests {

#[test]
fn delete_object_owned_handle_consumes_exact_provenance_and_releases_once() {
dynwinrt::system_helpers::GdiObjectDeleter::resolve().unwrap();
let bitmap = unsafe { windows::Win32::Graphics::Gdi::CreateBitmap(1, 1, 1, 1, None) };
assert!(!bitmap.is_invalid());
let ptr = bitmap.0;
Expand Down Expand Up @@ -6631,6 +6633,7 @@ mod tests {

#[test]
fn delete_object_owned_handle_drop_releases_bitmap() {
dynwinrt::system_helpers::GdiObjectDeleter::resolve().unwrap();
let bitmap = unsafe { windows::Win32::Graphics::Gdi::CreateBitmap(1, 1, 1, 1, None) };
assert!(!bitmap.is_invalid());
let pointer = bitmap.0;
Expand Down
Loading
Loading