//! `#[gnauth(secured)]`/`#[gnauth(token_only)]`/`#[gnauth(disabled)]`: //! compile-time tags spanning this API's whole auth spectrum. //! //! - `disabled`: handlers that intentionally require no token at all //! (e.g. a health check or the version endpoint). Marks the //! decision as deliberate, not an oversight. //! - `token_only`: handlers that require a valid bearer token but //! never make the gn-auth resource-authorization round trip -- //! everything gated purely by "is this caller who they say they //! are," not "is this specific resource visible to them." //! - `secured`: handlers that must make the gn-auth resource- //! authorization round trip -- not just hold a valid bearer token -- //! before returning data. Use it only on endpoints that can share //! actual trait/probeset *values*; metadata- or listing-only //! endpoints that happen to gate the same way (e.g. `traits`, //! `dataset_probesets`, `group_traits`) are deliberately left //! untagged by either `secured` or `token_only` -- they're a fourth, //! unlabeled case (token + round trip, but no values), since neither //! tag's check would describe them honestly. //! //! A proc-macro attribute only ever sees tokens, never types, so none //! of these can verify the real guarantee by itself -- each is a //! *textual* sanity check on top of the real mechanism, so an endpoint //! can't silently drift out of sync with its tag: //! - `secured` requires the signature to take `AuthToken` and the body //! to mention `Authorized`, the capability type only `auth::check` //! can produce (its field is private, so it can't be fabricated //! outside `src/auth.rs` -- see that module). //! - `token_only` requires the signature to take `AuthToken`, and the //! body to *not* mention `Authorized` -- if it started doing the //! round trip, the tag is now wrong and should become `secured` (or //! be removed, if the endpoint stays metadata-only). //! - `disabled` requires the signature to *not* take `AuthToken`. //! //! All three are markers, not wrappers: the function is re-emitted //! unchanged, so they cost nothing at runtime. //! //! The crate also hosts one *wrapper* attribute, `#[compute_gate(...)]`, //! which makes the endpoint's *light* claim on its gate and runs the body //! in the task that holds it. The body keeps one gate call of its own -- //! `__gn4_claim.claim_slot_or_busy(individuals, rid)`, where the panel size //! is first known -- because only the handler can tell a large computation //! from a small one, and the gate exists for the large ones. (The crate name //! predates that; a rename to `gn-macros` would be honest, but it would //! touch every `use gnauth_macros::...` for no behavioural change.) use proc_macro::TokenStream; use quote::{quote, ToTokens}; use syn::punctuated::Punctuated; use syn::parse::Parser; use syn::spanned::Spanned; use syn::{parse_macro_input, Expr, FnArg, Ident, ItemFn, LitStr, Meta, Token}; #[proc_macro_attribute] pub fn gnauth(attr: TokenStream, item: TokenStream) -> TokenStream { let attr_str = attr.to_string(); let input = parse_macro_input!(item as ItemFn); let sig_text = input.sig.to_token_stream().to_string(); match attr_str.as_str() { "secured" => { if !sig_text.contains("AuthToken") { return syn::Error::new_spanned( &input.sig, "#[gnauth(secured)] requires an `AuthToken` parameter: \ this handler must require a valid bearer token", ) .to_compile_error() .into(); } let body_text = input.block.to_token_stream().to_string(); if !body_text.contains("Authorized") { return syn::Error::new_spanned( &input.sig, "#[gnauth(secured)] requires the handler to use `auth::Authorized` \ (produced only by auth::check, i.e. the gn-auth resource-authorization \ round trip): this handler is tagged as sharing secured data but never \ mentions it", ) .to_compile_error() .into(); } } "token_only" => { if !sig_text.contains("AuthToken") { return syn::Error::new_spanned( &input.sig, "#[gnauth(token_only)] requires an `AuthToken` parameter: \ this handler must require a valid bearer token", ) .to_compile_error() .into(); } let body_text = input.block.to_token_stream().to_string(); if body_text.contains("Authorized") { return syn::Error::new_spanned( &input.sig, "#[gnauth(token_only)] asserts this handler never makes the gn-auth \ resource-authorization round trip, but its body mentions \ `auth::Authorized`: retag it `#[gnauth(secured)]` if it now shares \ values, or remove the tag if it's metadata-only", ) .to_compile_error() .into(); } } "disabled" => { if sig_text.contains("AuthToken") { return syn::Error::new_spanned( &input.sig, "#[gnauth(disabled)] asserts this handler takes no `AuthToken`: \ remove the tag (or the parameter) since it now does", ) .to_compile_error() .into(); } } _ => { return syn::Error::new( proc_macro2::Span::call_site(), "expected `#[gnauth(secured)]`, `#[gnauth(token_only)]` or \ `#[gnauth(disabled)]`", ) .to_compile_error() .into(); } } quote! { #input }.into() } /// `#[compute_gate(gate, endpoint = "name", status = "/compute/…/status", /// run_id = )]`: run this handler's body behind one compute slot. /// /// The handler must take a `Ctx` (for the request id) and an `AuthToken` /// (every compute endpoint is token-only, so the subject is always there); /// with those the attribute expands to /// /// ```ignore /// let claim = compute_gate::GATE().claim_or_busy(&token.sub, run_id, ctx.request_info(), endpoint, status).await?; /// compute_gate::GATE().run(claim, async move { /* the original body */ }).await /// ``` /// /// `run_id` (an `Option<&str>`, e.g. `params.id.as_deref()`) is what the /// busy error quotes and links to; `endpoint` defaults to the gate's own /// name and `status` to `/compute/{endpoint}/status`, which is right for /// `/compute/gemma` and needs overriding for a runner whose status lives /// under a different path (raxanan shares `/compute/gemma/status`). /// /// The body moves into a spawned task that owns the claim, so the slot is /// held for as long as the job is, not as long as the request is. #[proc_macro_attribute] pub fn compute_gate(attr: TokenStream, item: TokenStream) -> TokenStream { let input = parse_macro_input!(item as ItemFn); // `gate`, then optional `endpoint = "..."`, `status = "..."`, // `run_id = `. let args = match Punctuated::::parse_terminated.parse(attr) { Ok(args) => args, Err(error) => return error.to_compile_error().into(), }; let mut gate: Option = None; let mut endpoint: Option = None; let mut status: Option = None; let mut run_id: Option = None; let mut label: Option = None; for meta in args { match &meta { Meta::Path(path) if gate.is_none() => { let Some(ident) = path.get_ident() else { return syn::Error::new_spanned(path, "expected a gate name, e.g. `gemma`") .to_compile_error() .into(); }; gate = Some(ident.clone()); } Meta::NameValue(named) => { let Some(ident) = named.path.get_ident() else { return syn::Error::new_spanned(&named.path, "unknown argument") .to_compile_error() .into(); }; match ident.to_string().as_str() { "endpoint" => match &named.value { Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(text), .. }) => { endpoint = Some(text.clone()) } other => { return syn::Error::new_spanned(other, "endpoint must be a string") .to_compile_error() .into(); } }, "status" => match &named.value { Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(text), .. }) => { status = Some(text.clone()) } other => { return syn::Error::new_spanned(other, "status must be a string") .to_compile_error() .into(); } }, "label" => match &named.value { Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(text), .. }) => { label = Some(text.clone()) } other => { return syn::Error::new_spanned(other, "label must be a string") .to_compile_error() .into(); } }, "run_id" => run_id = Some(named.value.clone()), other => { return syn::Error::new_spanned(ident, format!("unknown argument `{other}`")) .to_compile_error() .into(); } } } other => { return syn::Error::new_spanned(other, "expected a gate name or name = value") .to_compile_error() .into(); } } } let Some(gate) = gate else { return syn::Error::new(proc_macro2::Span::call_site(), "expected a gate name, e.g. `#[compute_gate(gemma)]`") .to_compile_error() .into(); }; let endpoint = endpoint.unwrap_or_else(|| LitStr::new(&gate.to_string(), gate.span())); let status = status.unwrap_or_else(|| { LitStr::new( &format!("/compute/{}/status", gate), proc_macro2::Span::call_site(), ) }); let run_id = run_id.unwrap_or_else(|| syn::parse_quote!(None)); let label = label.unwrap_or_else(|| endpoint.clone()); // The two parameters the wrapper needs, by whatever they were named. let mut ctx: Option = None; let mut token: Option = None; for argument in &input.sig.inputs { let FnArg::Typed(typed) = argument else { continue; }; let type_text = typed.ty.to_token_stream().to_string(); let pattern = typed.pat.to_token_stream().to_string(); if type_text.contains("Ctx") { ctx = Some(Ident::new(&pattern, typed.pat.span())); } else if type_text.contains("AuthToken") { token = Some(Ident::new(&pattern, typed.pat.span())); } } // The `Ctx` is still required -- every gated handler builds its // envelope (and its promotion's request id) from it. let (Some(_ctx), Some(token)) = (ctx, token) else { return syn::Error::new_spanned( &input.sig, "#[compute_gate] needs a `Ctx` parameter (for the request id) and an `AuthToken`: \ every compute endpoint is token-only, and the token's sub is the subject the slot \ is claimed for", ) .to_compile_error() .into(); }; let attributes = &input.attrs; let visibility = &input.vis; let signature = &input.sig; let statements = &input.block.stmts; quote! { #(#attributes)* #visibility #signature { // A *light* claim: the panel is not resolved yet, so the gate // cannot know whether this job is large. The body promotes it // with `__gn4_claim.claim_slot_or_busy(individuals, rid)` where // the size is known -- a small job never touches the semaphore // -- and hands it to `run(...)` around the call that computes, // so the slot outlives a client disconnect. let mut __gn4_claim = crate::compute_gate::#gate().claim_light( &#token.sub, #run_id, #endpoint, #label, #status, ); #(#statements)* } } .into() }