about summary refs log tree commit diff
path: root/gnauth-macros/src/lib.rs
blob: 5720234dcc31da4d268a2d9fb60c564152899667 (plain)
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
//! `#[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 = <expr>)]`: 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 = <expr>`.
    let args = match Punctuated::<Meta, Token![,]>::parse_terminated.parse(attr) {
        Ok(args) => args,
        Err(error) => return error.to_compile_error().into(),
    };
    let mut gate: Option<Ident> = None;
    let mut endpoint: Option<LitStr> = None;
    let mut status: Option<LitStr> = None;
    let mut run_id: Option<Expr> = None;
    let mut label: Option<LitStr> = 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<Ident> = None;
    let mut token: Option<Ident> = 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()
}