diff --git a/app/Cargo.lock b/app/Cargo.lock index 3c6a590c..0435d0d0 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -23,7 +23,7 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" dependencies = [ - "crypto-common", + "crypto-common 0.2.2", "inout", ] @@ -35,7 +35,7 @@ checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" dependencies = [ "cipher", "cpubits", - "cpufeatures", + "cpufeatures 0.3.1", ] [[package]] @@ -73,6 +73,15 @@ version = "0.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b" +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + [[package]] name = "anstream" version = "1.0.0" @@ -151,6 +160,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "atoi" version = "2.0.0" @@ -287,6 +307,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block-buffer" version = "0.12.1" @@ -399,6 +428,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chacha20" version = "0.10.2" @@ -406,18 +441,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.3.1", "rand_core 0.10.1", ] +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link 0.2.1", +] + [[package]] name = "cipher" version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.12.1", + "crypto-common 0.2.2", "inout", ] @@ -566,6 +613,15 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "cpufeatures" version = "0.3.1" @@ -646,6 +702,16 @@ dependencies = [ "winapi", ] +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "crypto-common" version = "0.2.2" @@ -687,15 +753,25 @@ version = "1.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abd57806937c9cc163efc8ea3910e00a62e2aeb0b8119f1793a978088f8f6b04" +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.6", +] + [[package]] name = "digest" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer", + "block-buffer 0.12.1", "const-oid", - "crypto-common", + "crypto-common 0.2.2", "ctutils", ] @@ -972,8 +1048,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -995,9 +1073,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -1068,7 +1148,7 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "digest", + "digest 0.11.3", ] [[package]] @@ -1164,6 +1244,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", + "webpki-roots", ] [[package]] @@ -1190,6 +1271,30 @@ dependencies = [ "tracing", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "icu_collections" version = "2.4.0" @@ -1378,7 +1483,7 @@ dependencies = [ "indexmap", "inertia-laravel-rust-macros", "jiff 1.1.0", - "reqwest", + "reqwest 0.13.5", "serde", "serde_json", "tower-layer", @@ -1686,7 +1791,7 @@ dependencies = [ "serde_json", "serde_urlencoded", "sha1", - "sha2", + "sha2 0.11.3", "shlex", "signal-hook", "sqlx", @@ -1718,7 +1823,7 @@ dependencies = [ "laravel-rust-redis", "serde", "serde_json", - "sha2", + "sha2 0.11.3", "thiserror", "tokio", "tracing", @@ -1739,7 +1844,7 @@ dependencies = [ "laravel-rust-core", "mime_guess", "percent-encoding", - "reqwest", + "reqwest 0.13.5", "rustls", "serde", "serde_json", @@ -1811,7 +1916,7 @@ dependencies = [ "rustls", "serde", "serde_json", - "sha2", + "sha2 0.11.3", "sqlx", "thiserror", "tokio", @@ -1959,12 +2064,12 @@ dependencies = [ "num-bigint 0.5.1", "percent-encoding", "regex", - "reqwest", + "reqwest 0.13.5", "serde", "serde_json", "serde_urlencoded", "sha1", - "sha2", + "sha2 0.11.3", "subtle", "sync_wrapper", "tempfile", @@ -2072,7 +2177,7 @@ dependencies = [ "laravel-rust-database", "laravel-rust-queue-macros", "laravel-rust-redis", - "reqwest", + "reqwest 0.13.5", "serde", "serde_json", "thiserror", @@ -2132,7 +2237,7 @@ dependencies = [ "libc", "serde", "serde_json", - "sha2", + "sha2 0.11.3", "shlex", "tokio", "tracing", @@ -2157,7 +2262,7 @@ dependencies = [ "laravel-rust-queue", "serde", "serde_json", - "sha2", + "sha2 0.11.3", "tokio", "ulid", "uuid", @@ -2288,6 +2393,12 @@ version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "mail-builder" version = "2.0.1" @@ -2326,7 +2437,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" dependencies = [ "cfg-if", - "digest", + "digest 0.11.3", ] [[package]] @@ -2466,6 +2577,77 @@ dependencies = [ "autocfg", ] +[[package]] +name = "oauth-provider" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b0f78829493c60f76b32253acbcbddf67f358262f85e6c042e80cb706e7dbbe" +dependencies = [ + "async-trait", + "base64 0.22.1", + "chrono", + "hex", + "rand 0.9.5", + "serde", + "serde_json", + "sha2 0.10.9", + "subtle", + "thiserror", + "tracing", + "unicode-normalization", + "url", + "uuid", +] + +[[package]] +name = "oauth-provider-axum" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a63dafd8ad1cd3e468152a257a09791d62f2c6d0eed8e73fce2442b5ce49a75" +dependencies = [ + "async-trait", + "axum", + "oauth-provider", + "serde_json", + "url", +] + +[[package]] +name = "oauth-provider-laravel" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef48df94542f862f18f6cb65afc7e208d6f7b198e7488a45a606934bbf69b27a" +dependencies = [ + "async-trait", + "axum", + "chrono", + "hex", + "laravel-rust", + "oauth-provider", + "oauth-provider-axum", + "oauth-provider-mcp", + "serde", + "serde_json", + "sha2 0.10.9", + "tower", + "tracing", + "url", +] + +[[package]] +name = "oauth-provider-mcp" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55162b5882d6f3a986d437e51bcd86d523de01dc7026534b18da5c8121db069e" +dependencies = [ + "async-trait", + "oauth-provider", + "reqwest 0.12.28", + "thiserror", + "tokio", + "url", +] + [[package]] name = "objc2-core-foundation" version = "0.3.2" @@ -2575,7 +2757,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" dependencies = [ "cpubits", - "cpufeatures", + "cpufeatures 0.3.1", "universal-hash", ] @@ -2629,6 +2811,62 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.4", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -2696,6 +2934,15 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -2734,6 +2981,44 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http 0.6.11", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + [[package]] name = "reqwest" version = "0.13.5" @@ -2794,6 +3079,12 @@ version = "0.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustc_version" version = "0.4.1" @@ -2858,6 +3149,7 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ + "web-time", "zeroize", ] @@ -3039,8 +3331,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", ] [[package]] @@ -3050,8 +3353,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -3185,7 +3488,7 @@ dependencies = [ "rustls", "serde", "serde_json", - "sha2", + "sha2 0.11.3", "smallvec", "thiserror", "time", @@ -3225,7 +3528,7 @@ dependencies = [ "quote", "serde", "serde_json", - "sha2", + "sha2 0.11.3", "sqlx-core", "sqlx-mysql", "sqlx-postgres", @@ -3246,7 +3549,7 @@ dependencies = [ "byteorder", "bytes", "crc", - "digest", + "digest 0.11.3", "dotenvy", "either", "futures-core", @@ -3256,7 +3559,7 @@ dependencies = [ "percent-encoding", "serde", "sha1", - "sha2", + "sha2 0.11.3", "sqlx-core", "thiserror", "time", @@ -3292,7 +3595,7 @@ dependencies = [ "rand 0.10.4", "serde", "serde_json", - "sha2", + "sha2 0.11.3", "smallvec", "sqlx-core", "stringprep", @@ -3816,7 +4119,7 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" dependencies = [ - "crypto-common", + "crypto-common 0.2.2", "ctutils", ] @@ -3865,6 +4168,7 @@ version = "1.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" dependencies = [ + "getrandom 0.4.3", "js-sys", "serde_core", "wasm-bindgen", @@ -3892,9 +4196,13 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" name = "visualci-app" version = "0.0.0" dependencies = [ + "axum", + "hex", "laravel-rust", + "oauth-provider-laravel", "serde", "serde_json", + "sha2 0.10.9", "tokio", ] @@ -4081,6 +4389,41 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.2.1", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.2.1" @@ -4093,6 +4436,24 @@ version = "0.101.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4" +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-sys" version = "0.52.0" diff --git a/app/Cargo.toml b/app/Cargo.toml index 1d3aaaea..550ccded 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -24,8 +24,13 @@ path = "src/main.rs" [dependencies] # Pinned exactly: each 0.x minor of Laravel Rust may break, and upgrades are deliberate. laravel-rust = { version = "=0.1.4", features = ["database-postgres", "minijinja"] } +# The same axum Laravel Rust runs on, for extractors (auth::Principal) +axum = "0.8" +hex = "0.4" +oauth-provider-laravel = { version = "0.1", features = ["postgres"] } serde = { version = "1", features = ["derive"] } serde_json = "1" +sha2 = "0.10" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } [dev-dependencies] diff --git a/app/database/migrations/0001_01_01_000000_create_users_table.rs b/app/database/migrations/0001_01_01_000000_create_users_table.rs index 9bb032dc..a6bc3567 100644 --- a/app/database/migrations/0001_01_01_000000_create_users_table.rs +++ b/app/database/migrations/0001_01_01_000000_create_users_table.rs @@ -1,14 +1,22 @@ use laravel::db::AnyTransaction; +/// People, and their sessions. Everyone signs in through a forge (GitHub or GitLab): `password` stays empty, and the +/// forge accounts are in `identities`. pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { tx.schema() .create("users", |table| { table.id(); + table.uuid("pid").unique(); table.string("name"); table.string("email").unique(); table.timestamp("email_verified_at").nullable(); - table.string("password"); + table.string("password").default(""); table.remember_token(); + table.text("avatar_url").nullable(); + // VisualCI's own team: the admin MCP endpoint and staff pages + table.boolean("staff").default(false); + // How they signed up ("github", "github, from an MCP client's sign-in"), for the team's sign-up notice + table.text("signup_via").nullable(); table.timestamps(); }) .await?; diff --git a/app/database/migrations/2026_12_03_000100_create_auth_tables.rs b/app/database/migrations/2026_12_03_000100_create_auth_tables.rs new file mode 100644 index 00000000..9ad341ed --- /dev/null +++ b/app/database/migrations/2026_12_03_000100_create_auth_tables.rs @@ -0,0 +1,63 @@ +use laravel::db::AnyTransaction; + +/// Forge accounts, personal and project tokens, and the waitlist (sc-8900, the auth side). `project_tokens.project_id` +/// gets its foreign key once the domain tables exist. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.schema() + .create("identities", |table| { + table.id(); + table.foreign_id("user_id").constrained().cascade_on_delete(); + // "github" or "gitlab"; `site` is a self-managed GitLab's host, empty for gitlab.com and GitHub + table.string("forge"); + table.string("site").default(""); + table.string("forge_user_id"); + table.string("login"); + table.timestamps(); + table.unique(["forge", "site", "forge_user_id"]); + }) + .await?; + + // Personal access tokens (`vcu_…`): whatever their user can do, in every organization they belong to + tx.schema() + .create("user_tokens", |table| { + table.id(); + table.foreign_id("user_id").constrained().cascade_on_delete(); + table.string("name"); + // SHA-256 of the token, hex; the token itself is shown once + table.string("token_hash").unique(); + table.string("token_prefix"); + table.timestamp("last_used_at").nullable(); + table.timestamps(); + }) + .await?; + + // Project tokens (`vci_…`): CI's, for one project + tx.schema() + .create("project_tokens", |table| { + table.id(); + table.big_integer("project_id").index(); + table.string("name"); + table.string("token_hash").unique(); + table.string("token_prefix"); + table.timestamp("last_used_at").nullable(); + table.timestamps(); + }) + .await?; + + // Closed sign-ups: someone new who signs in is written here instead of getting an account + tx.schema() + .create("waitlist", |table| { + table.id(); + table.string("forge"); + table.string("site").default(""); + table.string("forge_user_id"); + table.string("login"); + table.text("name").nullable(); + table.text("email").nullable(); + // "web", or "mcp: " + table.text("source"); + table.timestamps(); + table.unique(["forge", "site", "forge_user_id"]); + }) + .await +} diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 75e4f891..7780bf8e 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -1,2 +1,236 @@ -//! Who a request acts for (owned by `visualci subdomains`, sc-8900): `Principal`, a user or a project token, with its -//! access checks. A placeholder until the auth stub lands. +//! Who a request acts for (owned by `visualci subdomains`, sc-8900): a [`Principal`], a person or a project token, +//! with the access checks every API, MCP and web handler uses. +//! +//! A handler takes `Principal` like any extractor. It's found, in order, from: +//! 1. the signed-in user: the session on web routes, or the OAuth token on MCP routes (behind `Authenticate::via` +//! with oauth-provider-laravel's guard, which also names the client, see [`Client`]); +//! 2. a bearer token: a personal token (`vcu_…`) acts as its user, a project token (`vci_…`) for its project. +//! +//! Nobody found: `401`. + +use axum::extract::FromRequestParts; +use axum::http::request::Parts; +use laravel::auth::Auth; +use laravel::db; + +use crate::models::{ProjectToken, User, UserToken, token_hash}; + +/// What someone may do in a project's organization, lowest first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Role { + /// Sees builds and snapshots; changes nothing. + Read, + /// Everything a build needs: uploads, review and approval. + Member, + /// Also settings, projects, tokens, billing and members. + Admin, +} + +impl Role { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Read => "read", + Self::Member => "member", + Self::Admin => "admin", + } + } + + #[must_use] + pub fn parse(s: &str) -> Option { + match s { + "read" => Some(Self::Read), + "member" => Some(Self::Member), + "admin" => Some(Self::Admin), + _ => None, + } + } +} + +/// Anything that belongs to a project: the domain's `Project` model implements it (and builds or snapshots can, by +/// their project), so the checks here don't depend on those models. +pub trait InProject { + fn project_id(&self) -> i64; + fn organization_id(&self) -> i64; +} + +/// A project as the checks need it, for callers that only have the IDs. +#[derive(Clone, Copy, Debug)] +pub struct ProjectRef { + pub id: i64, + pub organization_id: i64, +} + +impl InProject for ProjectRef { + fn project_id(&self) -> i64 { + self.id + } + fn organization_id(&self) -> i64 { + self.organization_id + } +} + +/// Who a request acts for. +#[derive(Clone, Debug)] +pub enum Principal { + /// A person: signed in, through an MCP client's OAuth token, or with a personal token. + User { user: Box, via: Via }, + /// A project token: CI, for one project. + Project { project_id: i64, token_id: i64, token_name: String }, +} + +/// How a person's request reached us. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Via { + /// The web app's session. + Session, + /// An MCP (or other OAuth) client they approved. + OAuth { client_id: String }, + /// One of their personal tokens. + Token { token_id: i64, name: String }, +} + +/// What acted, for attributing a review or an upload (`reviews.source`, `client_id`, `token_name`): "Claude Code for +/// Ada", "a project token (CI)". The client's display name is looked up from `client_id` by whoever shows it. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +pub struct Client { + /// `web`, `mcp`, `token` (a personal token) or `project_token`. + pub source: &'static str, + pub client_id: Option, + pub token_name: Option, +} + +impl Principal { + /// The person, when it's one. + #[must_use] + pub fn user(&self) -> Option<&User> { + match self { + Self::User { user, .. } => Some(user), + Self::Project { .. } => None, + } + } + + /// What acted. + #[must_use] + pub fn client(&self) -> Client { + match self { + Self::User { via: Via::Session, .. } => Client { source: "web", client_id: None, token_name: None }, + Self::User { via: Via::OAuth { client_id }, .. } => { + Client { source: "mcp", client_id: Some(client_id.clone()), token_name: None } + } + Self::User { via: Via::Token { name, .. }, .. } => { + Client { source: "token", client_id: None, token_name: Some(name.clone()) } + } + Self::Project { token_name, .. } => { + Client { source: "project_token", client_id: None, token_name: Some(token_name.clone()) } + } + } + } + + /// Their role in the project's organization, or `None` when they have none. A project token is a member of its + /// own project and nothing else. + /// + /// # Errors + /// On a database error. + pub async fn role_in(&self, project: &impl InProject) -> laravel::Result> { + match self { + Self::Project { project_id, .. } => Ok((*project_id == project.project_id()).then_some(Role::Member)), + Self::User { user, .. } => { + let (org, user_id) = (project.organization_id(), user.id); + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {user_id}") + .scalar() + .await?; + Ok(role.as_deref().and_then(Role::parse)) + } + } + } + + /// Whether they have at least `role` in the project. + /// + /// # Errors + /// On a database error. + pub async fn can(&self, role: Role, project: &impl InProject) -> laravel::Result { + Ok(self.role_in(project).await?.is_some_and(|r| r >= role)) + } + + /// The IDs of the projects they can see: every project of their organizations, or a project token's own. + /// + /// # Errors + /// On a database error. + pub async fn project_ids_visible(&self) -> laravel::Result> { + match self { + Self::Project { project_id, .. } => Ok(vec![*project_id]), + Self::User { user, .. } => { + let user_id = user.id; + db::query!( + "SELECT p.id FROM projects p JOIN memberships m ON m.organization_id = p.organization_id \ + WHERE m.user_id = {user_id} ORDER BY p.id" + ) + .select_as::() + .await + } + } + } + + /// The principal a request's bearer token names, if it names one. + /// + /// # Errors + /// On a database error. + pub async fn from_token(token: &str) -> laravel::Result> { + let hash = token_hash(token); + if token.starts_with("vci_") { + let Some(t) = ProjectToken::first_where(ProjectToken::token_hash.eq(&hash)).await? else { return Ok(None) }; + return Ok(Some(Self::Project { project_id: t.project_id, token_id: t.id, token_name: t.name })); + } + if token.starts_with("vcu_") { + let Some(t) = UserToken::first_where(UserToken::token_hash.eq(&hash)).await? else { return Ok(None) }; + let Some(user) = User::find(t.user_id).await? else { return Ok(None) }; + return Ok(Some(Self::User { user: Box::new(user), via: Via::Token { token_id: t.id, name: t.name } })); + } + Ok(None) + } +} + +impl laravel::auth::Authorizable for Principal {} + +impl FromRequestParts for Principal { + type Rejection = laravel::Error; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + // The session's user, or the OAuth token's behind Authenticate::via (a route without a session or guard has + // no user here) + if let Ok(auth) = as FromRequestParts>::from_request_parts(parts, state).await + && let Some(user) = auth.user().await? + { + let via = match parts.extensions.get::() { + Some(grant) => Via::OAuth { client_id: grant.client_id().to_string() }, + None => Via::Session, + }; + return Ok(Self::User { user: Box::new(user), via }); + } + let bearer = parts + .headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(str::trim); + if let Some(token) = bearer + && let Some(principal) = Self::from_token(token).await? + { + return Ok(principal); + } + Err(laravel::abort(401)) + } +} + +/// `GET /api/v1/whoami`: who the request acts for, and how. +pub async fn whoami(principal: Principal) -> laravel::Result> { + let client = principal.client(); + let who = match &principal { + Principal::User { user, .. } => serde_json::json!({ "kind": "user", "id": user.pid, "name": user.name }), + Principal::Project { project_id, .. } => serde_json::json!({ "kind": "project", "project_id": project_id }), + }; + Ok(axum::Json(serde_json::json!({ "principal": who, "client": client }))) +} diff --git a/app/src/http/api.rs b/app/src/http/api.rs index 198ddddc..ec4c7bd4 100644 --- a/app/src/http/api.rs +++ b/app/src/http/api.rs @@ -7,5 +7,6 @@ pub fn routes(route: &mut Router) { route.get("/v1/version", async || { Json(json!({ "visualci": env!("CARGO_PKG_VERSION"), "laravel": laravel::VERSION })) }); + route.get("/v1/whoami", crate::auth::whoami); route.fallback(async || laravel::abort(404)); } diff --git a/app/src/lib.rs b/app/src/lib.rs index 06b81eb8..0c096a64 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -11,9 +11,12 @@ use laravel::Application; use laravel::foundation::ApplicationBuilder; pub fn configure() -> ApplicationBuilder { - Application::configure().with_migrations(laravel::db::migrations!("database/migrations")).with_routing( - |routing, _| { + Application::configure() + .with_migrations(laravel::db::migrations!("database/migrations")) + .with_auth(|auth, _| { + auth.session::>(); + }) + .with_routing(|routing, _| { routing.api(http::api::routes).health("/up"); - }, - ) + }) } diff --git a/app/src/models/mod.rs b/app/src/models/mod.rs index 33c70398..10805441 100644 --- a/app/src/models/mod.rs +++ b/app/src/models/mod.rs @@ -1 +1,7 @@ -//! Models. +//! Models. The auth side's (users, tokens) are `visualci subdomains`'; the domain's are `visualci features'` (sc-8900). + +mod tokens; +mod user; + +pub use tokens::{ProjectToken, UserToken, token_hash}; +pub use user::User; diff --git a/app/src/models/tokens.rs b/app/src/models/tokens.rs new file mode 100644 index 00000000..34e476ce --- /dev/null +++ b/app/src/models/tokens.rs @@ -0,0 +1,37 @@ +use laravel::model::model; +use laravel::time::Timestamp; + +/// A personal access token (`vcu_…`): whatever its user can do, in every organization they belong to. +#[model] +pub struct UserToken { + pub id: i64, + pub user_id: i64, + pub name: String, + #[serde(skip)] + pub token_hash: String, + pub token_prefix: String, + pub last_used_at: Option, + pub created_at: Timestamp, + pub updated_at: Timestamp, +} + +/// A project token (`vci_…`): CI's, for one project. +#[model] +pub struct ProjectToken { + pub id: i64, + pub project_id: i64, + pub name: String, + #[serde(skip)] + pub token_hash: String, + pub token_prefix: String, + pub last_used_at: Option, + pub created_at: Timestamp, + pub updated_at: Timestamp, +} + +/// The SHA-256 a token is stored as, hex. +#[must_use] +pub fn token_hash(token: &str) -> String { + use sha2::Digest; + hex::encode(sha2::Sha256::digest(token.as_bytes())) +} diff --git a/app/src/models/user.rs b/app/src/models/user.rs new file mode 100644 index 00000000..bc20b977 --- /dev/null +++ b/app/src/models/user.rs @@ -0,0 +1,26 @@ +use laravel::auth::{Authenticatable, RememberToken}; +use laravel::hash::PasswordHash; +use laravel::model::model; +use laravel::str::Uuid; +use laravel::time::Timestamp; + +/// A person. Everyone signs in through a forge (their forge accounts are `Identity` rows), and MCP clients act for +/// them once they approve a connection. +#[model] +#[derive(Authenticatable)] +pub struct User { + pub id: i64, + pub pid: Uuid, + pub name: String, + pub email: String, + pub email_verified_at: Option, + #[serde(skip)] + pub password: PasswordHash, + #[serde(skip)] + pub remember_token: Option, + pub avatar_url: Option, + pub staff: bool, + pub signup_via: Option, + pub created_at: Timestamp, + pub updated_at: Timestamp, +} diff --git a/app/tests/auth.rs b/app/tests/auth.rs new file mode 100644 index 00000000..60b401f4 --- /dev/null +++ b/app/tests/auth.rs @@ -0,0 +1,95 @@ +//! auth::Principal: who a request acts for, from the session or a bearer token, and what they may do. + +use app::auth::{Principal, ProjectRef, Role, Via}; +use app::models::{User, token_hash}; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn user(email: &str) -> laravel::Result { + create!(User { pid: laravel::str::uuid7(), name: "Ada", email: email, password: "", staff: false }).await +} + +/// The memberships table belongs to the domain migrations (sc-8900); until they land, the test makes a stand-in. +async fn memberships() -> laravel::Result<()> { + db::query!( + "CREATE TABLE IF NOT EXISTS memberships (organization_id BIGINT NOT NULL, user_id BIGINT NOT NULL, role TEXT NOT NULL)" + ) + .statement() + .await?; + Ok(()) +} + +#[laravel::test] +async fn a_signed_in_user_is_the_principal(app: Application) -> laravel::Result<()> { + let ada = user("ada@example.com").await?; + app.get("/api/v1/whoami") + .acting_as(&ada) + .await + .assert_ok() + .assert_json_path("principal.kind", "user") + .assert_json_path("client.source", "web"); + Ok(()) +} + +#[laravel::test] +async fn tokens_name_their_user_or_project(app: Application) -> laravel::Result<()> { + let ada = user("ada@example.com").await?; + let (personal, project) = ("vcu_personal-test-token", "vci_project-test-token"); + let (ph, jh) = (token_hash(personal), token_hash(project)); + let ada_id = ada.id; + db::query!( + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({ada_id}, 'laptop', {ph}, 'vcu_pe', now(), now())" + ) + .insert() + .await?; + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES (7, 'CI', {jh}, 'vci_pr', now(), now())" + ) + .insert() + .await?; + + app.get("/api/v1/whoami") + .header("authorization", format!("Bearer {personal}")) + .await + .assert_ok() + .assert_json_path("principal.kind", "user") + .assert_json_path("client.source", "token") + .assert_json_path("client.token_name", "laptop"); + app.get("/api/v1/whoami") + .header("authorization", format!("Bearer {project}")) + .await + .assert_ok() + .assert_json_path("principal.project_id", 7) + .assert_json_path("client.source", "project_token"); + app.get("/api/v1/whoami").header("authorization", "Bearer vci_nope").await.assert_status(401); + app.get("/api/v1/whoami").await.assert_status(401); + Ok(()) +} + +#[laravel::test] +async fn roles_come_from_memberships_and_a_project_token_is_a_member_of_its_project( + _app: Application, +) -> laravel::Result<()> { + memberships().await?; + let ada = user("ada@example.com").await?; + let ada_id = ada.id; + db::query!("INSERT INTO memberships (organization_id, user_id, role) VALUES (1, {ada_id}, 'member')") + .insert() + .await?; + let ada = Principal::User { user: Box::new(ada), via: Via::Session }; + let mine = ProjectRef { id: 10, organization_id: 1 }; + let theirs = ProjectRef { id: 20, organization_id: 2 }; + assert_eq!(ada.role_in(&mine).await?, Some(Role::Member)); + assert!(ada.can(Role::Read, &mine).await? && ada.can(Role::Member, &mine).await?); + assert!(!ada.can(Role::Admin, &mine).await?); + assert!(!ada.can(Role::Read, &theirs).await?); + + let ci = Principal::Project { project_id: 10, token_id: 1, token_name: "CI".into() }; + assert!(ci.can(Role::Member, &mine).await? && !ci.can(Role::Admin, &mine).await?); + assert!(!ci.can(Role::Read, &ProjectRef { id: 11, organization_id: 1 }).await?, "only its own project"); + assert_eq!(ci.project_ids_visible().await?, vec![10]); + Ok(()) +}