rustclamp 1.0.0

A minimal synchronous entrypoint for Clamp applications.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#!/usr/bin/env python3
"""Enforce the initial dependency allowlist using resolved Cargo metadata."""

import argparse
import json
from pathlib import Path
import subprocess
import tempfile

# Every new edge requires prototype evidence and an explicit policy change.
ALLOWED = {
    # The optional `db` feature: rusqlite with bundled SQLite (ADR 0009). The
    # wasm-bindgen, js-sys and sqlite-wasm-rs entries build only for wasm32;
    # Cargo metadata resolves every target.
    "rustclamp": {
        "rustclamp-core", "rustclamp-kernel", "rustclamp-runtime",
        "allocator-api2", "bitflags", "bumpalo", "cc", "cfg-if", "equivalent",
        "fallible-iterator", "fallible-streaming-iterator", "find-msvc-tools",
        "foldhash", "hashbrown", "hashlink", "js-sys", "libsqlite3-sys",
        "once_cell", "pkg-config", "proc-macro2", "quote", "rsqlite-vfs",
        "rusqlite", "rustversion", "serde", "serde_core", "serde_derive",
        "shlex", "smallvec", "sqlite-wasm-rs", "syn", "thiserror",
        "thiserror-impl", "unicode-ident", "vcpkg", "wasm-bindgen",
        "wasm-bindgen-macro", "wasm-bindgen-macro-support",
        "wasm-bindgen-shared",
        # The optional `crypto` feature: RustCrypto argon2, chacha20poly1305,
        # sha2, hmac and base64ct, with getrandom (ADR 0010). r-efi is UEFI only.
        "aead", "argon2", "base64ct", "blake2", "block-buffer", "chacha20",
        "chacha20poly1305", "cipher", "cmov", "const-oid", "cpufeatures",
        "crypto-common", "ctutils", "digest", "getrandom", "hmac",
        "hybrid-array", "inout", "libc", "password-hash", "phc", "poly1305",
        "rand_core", "r-efi", "sha2", "typenum", "universal-hash",
        # The optional `markdown` feature: pulldown-cmark, HTML output only.
        "memchr", "pulldown-cmark", "pulldown-cmark-escape", "unicase",
        # The optional `regex` feature: the regex crate without its perf
        # features (ADR 0033). aho-corasick is never built: regex's `std`
        # feature names it weakly (`aho-corasick?/std`), which Cargo still
        # locks and reports in metadata (rust-lang/cargo#10801).
        "aho-corasick", "regex", "regex-automata", "regex-syntax",
        # The optional `mail` and `postgres` features: rustls with the ring
        # provider and webpki-roots (ADR 0015, ADR 0034). ring compiles C and assembly with cc; the
        # windows* and wasi entries build only for those targets.
        "ring", "rustls", "rustls-pki-types", "rustls-webpki", "subtle",
        "untrusted", "webpki-roots", "zeroize", "wasi", "windows-sys",
        "windows-targets", "windows_aarch64_gnullvm", "windows_aarch64_msvc",
        "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc",
        "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc",
        # The optional `db` feature's `#[derive(Model)]` (ADR 0014): a
        # proc-macro crate, so syn and quote run at compile time only.
        "rustclamp-macros",
    },
    "rustclamp-macros": {"proc-macro2", "quote", "syn", "unicode-ident"},
    "rustclamp-core": set(),
    "rustclamp-kernel": {"rustclamp-core"},
    "rustclamp-messaging": {
        "itoa", "memchr", "proc-macro2", "quote", "serde", "serde_core",
        "serde_derive", "serde_json", "syn", "unicode-ident", "zmij",
        "rustclamp-core",
    },
    "rustclamp-worker": {
        "itoa", "memchr", "proc-macro2", "quote", "serde", "serde_core",
        "serde_derive", "serde_json", "syn", "unicode-ident", "zmij",
        "rustclamp-core", "rustclamp-messaging",
        # Feature `service` (ADR 0020): runtime cancellation + Tokio; the runtime
        # entries are its closure under workspace feature unification.
        # Feature `sqlite` (ADR 0026): rusqlite with bundled SQLite, the same
        # closure the facade's `db` feature allows.
        "rusqlite", "allocator-api2", "bitflags", "bumpalo", "cc", "cfg-if",
        "equivalent", "fallible-iterator", "fallible-streaming-iterator",
        "find-msvc-tools", "foldhash", "hashbrown", "hashlink", "js-sys",
        "libsqlite3-sys", "once_cell", "pkg-config", "rsqlite-vfs",
        "rustversion", "shlex", "smallvec", "sqlite-wasm-rs", "thiserror",
        "thiserror-impl", "vcpkg", "wasm-bindgen", "wasm-bindgen-macro",
        "wasm-bindgen-macro-support", "wasm-bindgen-shared",
        "rustclamp-runtime", "tokio", "tokio-macros", "pin-project-lite",
        "bytes", "errno", "libc", "mio", "signal-hook-registry", "socket2",
        "wasi", "windows-link", "windows-sys",
        # Feature `mqtt` (ADR 0028): rumqttc without default features (no TLS).
        "rumqttc", "fixedbitset", "flume", "futures-core", "futures-sink",
        "futures-task", "futures-util", "lock_api", "log", "scopeguard",
        "slab", "spin", "tokio-stream", "tokio-util",
        # futures-util's default io and async-await-macro features, enabled when
        # the coordinated workspace unifies features.
        "futures-io", "futures-macro",
    },
    "rustclamp-scheduler": {
        "rustclamp-core",
        # Feature `tokio` (ADR 0020): Scheduler::run_until.
        "tokio", "tokio-macros", "pin-project-lite", "proc-macro2", "quote",
        "syn", "unicode-ident",
        "bytes", "errno", "libc", "mio", "signal-hook-registry", "socket2",
        "wasi", "windows-link", "windows-sys",
    },
    "rustclamp-runtime": {
    'bytes',
    'errno',
    'libc',
    'mio',
    'pin-project-lite',
    'proc-macro2',
    'quote',
    'rustclamp-core',
    'signal-hook-registry',
    'socket2',
    'syn',
    'tokio',
    'tokio-macros',
    'unicode-ident',
    'wasi',
    'windows-link',
    'windows-sys',
    },
    "rustclamp-http": {
    'atomic-waker',
    'axum',
    'axum-core',
    'bitflags',
    'bytes',
    'errno',
    'form_urlencoded',
    'futures-channel',
    'futures-core',
    'futures-io',
    'futures-macro',
    'futures-sink',
    'futures-task',
    'futures-util',
    'http',
    'http-body',
    'http-body-util',
    'httparse',
    'httpdate',
    'hyper',
    'hyper-util',
    'itoa',
    'libc',
    'log',
    'matchit',
    'memchr',
    'mime',
    'mio',
    'once_cell',
    'percent-encoding',
    'pin-project-lite',
    'proc-macro2',
    'quote',
    'rustclamp-core',
    'ryu',
    'serde',
    'serde_core',
    'serde_derive',
    'serde_json',
    'serde_path_to_error',
    'serde_urlencoded',
    'signal-hook-registry',
    'slab',
    'smallvec',
    'socket2',
    'syn',
    'sync_wrapper',
    'tokio',
    'tokio-macros',
    'tower',
    'tower-http',
    'tower-layer',
    'tower-service',
    'tracing',
    'tracing-attributes',
    'tracing-core',
    'unicode-ident',
    'wasi',
    'windows-link',
    'windows-sys',
    'zmij',
    # Feature `ws` (rustclamp/http#6): axum/ws pulls tokio-tungstenite and
    # tungstenite (SHA-1 handshake, random masking keys), and the WebSocket
    # tests use tokio-tungstenite as a client. r-efi, wasip2 and wit-bindgen
    # build only for UEFI and WASI.
    'base64', 'block-buffer', 'cfg-if', 'cpufeatures', 'crypto-common',
    'data-encoding', 'digest', 'generic-array', 'getrandom', 'ppv-lite86',
    'r-efi', 'rand', 'rand_chacha', 'rand_core', 'sha1', 'thiserror',
    'thiserror-impl', 'tokio-tungstenite', 'tungstenite', 'typenum',
    'version_check', 'wasip2', 'wit-bindgen', 'zerocopy', 'zerocopy-derive',
    # Feature `grpc` (ADR 0029): tonic without transport plus axum/http2 (h2);
    # the gRPC tests add tonic's client channel and prost/tonic-prost for one
    # hand-written message, so no protoc.
    'anyhow', 'async-trait', 'either', 'equivalent', 'fnv', 'h2', 'hashbrown',
    'hyper-timeout', 'indexmap', 'itertools', 'pin-project',
    'pin-project-internal', 'prost', 'prost-derive', 'tokio-stream',
    'tokio-util', 'tonic', 'tonic-prost', 'try-lock', 'want',
    # hashbrown's default hasher, enabled by the facade's hashlink when the
    # coordinated workspace unifies features.
    'foldhash',
    },
    "rustclamp-postgres": {
    # cipher, inout and const-oid are feature-unification artifacts, not
    # postgres edges: `--all-features` metadata resolves one graph, so the
    # chacha20/digest postgres already uses carry the `crypto` feature's
    # cipher and oid features (ADR 0010).
    'cipher',
    'const-oid',
    'inout',
    'allocator-api2',
    'atoi',
    'autocfg',
    'base64',
    'bitflags',
    'block-buffer',
    'byteorder',
    'bytes',
    'cc',
    'cfg-if',
    'chacha20',
    'cmov',
    'cpufeatures',
    'crc',
    'crc-catalog',
    'crossbeam-queue',
    'crossbeam-utils',
    'crypto-common',
    'ctutils',
    'digest',
    'displaydoc',
    'dotenvy',
    'either',
    'equivalent',
    'errno',
    'etcetera',
    'event-listener',
    'find-msvc-tools',
    'foldhash',
    'form_urlencoded',
    'futures-channel',
    'futures-core',
    'futures-intrusive',
    'futures-io',
    'futures-macro',
    'futures-sink',
    'futures-task',
    'futures-util',
    'generic-array',
    'getrandom',
    'hashbrown',
    'hashlink',
    'heck',
    'hex',
    'hkdf',
    'hmac',
    'hybrid-array',
    'icu_collections',
    'icu_locale_core',
    'icu_normalizer',
    'icu_normalizer_data',
    'icu_properties',
    'icu_properties_data',
    'icu_provider',
    'idna',
    'idna_adapter',
    'indexmap',
    'itoa',
    'libc',
    'litemap',
    'lock_api',
    'log',
    'md-5',
    'memchr',
    'mio',
    'num-traits',
    'once_cell',
    'parking',
    'parking_lot',
    'parking_lot_core',
    'percent-encoding',
    'pin-project-lite',
    'potential_utf',
    'proc-macro2',
    'quote',
    'r-efi',
    'rand',
    'rand_core',
    'redox_syscall',
    'ring',
    'rustclamp-core',
    'rustls',
    'rustls-pki-types',
    'rustls-webpki',
    'scopeguard',
    'serde',
    'serde_core',
    'serde_derive',
    'serde_json',
    'sha2',
    'shlex',
    'signal-hook-registry',
    'slab',
    'smallvec',
    'socket2',
    'sqlx',
    'sqlx-core',
    'sqlx-macros',
    'sqlx-macros-core',
    'sqlx-postgres',
    'stable_deref_trait',
    'stringprep',
    'subtle',
    'syn',
    'synstructure',
    'thiserror',
    'thiserror-impl',
    'tinystr',
    'tinyvec',
    'tinyvec_macros',
    'tokio',
    'tokio-macros',
    'tokio-stream',
    'tracing',
    'tracing-attributes',
    'tracing-core',
    'typenum',
    'unicode-bidi',
    'unicode-ident',
    'unicode-normalization',
    'unicode-properties',
    'untrusted',
    'url',
    'utf8_iter',
    'version_check',
    'wasi',
    'webpki-roots',
    'whoami',
    'windows-link',
    'windows-sys',
    'windows-targets',
    'windows_aarch64_gnullvm',
    'windows_aarch64_msvc',
    'windows_i686_gnu',
    'windows_i686_gnullvm',
    'windows_i686_msvc',
    'windows_x86_64_gnu',
    'windows_x86_64_gnullvm',
    'windows_x86_64_msvc',
    'writeable',
    'yoke',
    'yoke-derive',
    'zerofrom',
    'zerofrom-derive',
    'zeroize',
    'zerotrie',
    'zerovec',
    'zerovec-derive',
    'zmij',
    },
}
# Core's random source on Windows (`Reference::new`; Unix reads /dev/urandom):
# getrandom and what it can pull in on any target. rand_core comes from the
# facade's `sys_rng` feature through workspace feature unification.
CORE_RANDOM = {"getrandom", "cfg-if", "libc", "r-efi", "rand_core"}
for _name in ("rustclamp-core", "rustclamp-kernel", "rustclamp-runtime", "rustclamp-messaging",
              "rustclamp-scheduler", "rustclamp-worker"):
    ALLOWED[_name] |= CORE_RANDOM
OPTIONAL = {
    "rustclamp-runtime": {"tokio"},
    "rustclamp-worker": {"tokio", "rustclamp-runtime", "rusqlite", "rumqttc"},
    "rustclamp-scheduler": {"tokio"},
    "rustclamp": {"rustclamp-core", "rusqlite", "argon2", "chacha20poly1305", "sha2", "hmac", "base64ct", "getrandom", "pulldown-cmark", "regex", "rustclamp-macros", "rustls", "webpki-roots"},
}


def metadata(manifest):
    return json.loads(subprocess.check_output([
        "cargo", "metadata", "--format-version", "1", "--offline",
        "--all-features", "--manifest-path", str(manifest),
    ], text=True))


def violations(data):
    errors = []
    packages = {p["id"]: p for p in data["packages"]}
    for package in packages.values():
        name = package["name"]
        if name not in ALLOWED:
            continue
        # Declarations cover inactive target-specific and optional dependencies too.
        # Cargo reports the actual package name even for renamed dependencies.
        for dep in package["dependencies"]:
            if dep["name"] not in ALLOWED[name]:
                errors.append(f"{name} -> {dep['name']}: forbidden dependency")
            if dep["name"] in OPTIONAL.get(name, set()) and not dep["optional"]:
                errors.append(f"{name} -> {dep['name']}: dependency must remain optional")
            if dep.get("path") and dep["req"] == "*":
                errors.append(f"{name} -> {dep['name']}: path requires a version")
    # Check the complete resolved closure, not just immediate edges.
    nodes = {n["id"]: n for n in data["resolve"]["nodes"]}
    for package in packages.values():
        name = package["name"]
        if name not in ALLOWED:
            continue
        pending = list(nodes[package["id"]]["dependencies"])
        visited = set()
        while pending:
            dependency = pending.pop()
            if dependency in visited:
                continue
            visited.add(dependency)
            dep_name = packages[dependency]["name"]
            if dep_name not in ALLOWED[name]:
                errors.append(f"{name} reaches {dep_name}: forbidden transitive dependency")
            pending.extend(nodes[dependency]["dependencies"])
    return sorted(set(errors))


def self_test():
    # Real manifests, not hand-written metadata. These never access the registry.
    cases = [
        ("rustclamp-core", "tokio", "normal", False),
        ("rustclamp-core", "reqwest", "optional", False),
        ("rustclamp-core", "sqlx", "build", False),
        ("rustclamp-core", "async-openai", "target", False),
        ("rustclamp-kernel", "axum", "normal", False),
        ("rustclamp-runtime", "tokio", "normal", False),
        ("rustclamp-runtime", "tokio", "optional", True),
        ("rustclamp-kernel", "rustclamp", "dev", False),
        ("rustclamp-kernel", "rustclamp-core", "normal", True),
    ]
    for owner, dependency, kind, valid in cases:
        with tempfile.TemporaryDirectory(prefix="clamp-boundary-") as tmp:
            root = Path(tmp)
            (root / "Cargo.toml").write_text('[workspace]\nresolver="3"\nmembers=["owner", "dependency"]\n')
            for dirname, name in [("owner", owner), ("dependency", dependency)]:
                path = root / dirname
                (path / "src").mkdir(parents=True)
                (path / "src/lib.rs").write_text("")
                (path / "Cargo.toml").write_text(f'[package]\nname="{name}"\nversion="0.1.0"\nedition="2024"\n')
            section = {
                "normal": "dependencies", "optional": "dependencies",
                "build": "build-dependencies", "dev": "dev-dependencies",
                "target": "target.'cfg(target_os = \"none\")'.dependencies",
            }[kind]
            optional = ", optional=true" if kind == "optional" else ""
            with (root / "owner/Cargo.toml").open("a") as file:
                file.write(f'\n[{section}]\nhidden_alias={{package="{dependency}", version="0.1", path="../dependency"{optional}}}\n')
            errors = violations(metadata(root / "Cargo.toml"))
            if bool(errors) == valid:
                raise AssertionError(f"unexpected result for {owner} -> {dependency}: {errors}")
            print(f"fixture {'accepted' if valid else 'rejected'}: {owner} -> {dependency} ({kind})")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--manifest", type=Path, required=True)
    parser.add_argument("--self-test", action="store_true")
    parser.add_argument("--expect-current-members", action="store_true")
    args = parser.parse_args()
    if args.self_test:
        self_test()
    data = metadata(args.manifest)
    if args.expect_current_members:
        members = {p["name"] for p in data["packages"] if p["id"] in data["workspace_members"]}
        if members != set(ALLOWED):
            parser.error(f"unexpected workspace members: {sorted(members)}")
    errors = violations(data)
    if errors:
        raise SystemExit("\n".join(errors))
    print(f"Dependency boundaries passed ({len(data['packages'])} resolved packages).")


if __name__ == "__main__":
    main()