netget-tool 0.3.4

Network protocol stubbing toolkit: ~280 protocol servers and clients whose responses come from an LLM, a script, a static rule or a person.
Documentation
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! OAuth2 protocol actions implementation

use crate::llm::actions::{
    protocol_trait::{ActionResult, Protocol, Server},
    ActionDefinition, Parameter,
};
use crate::protocol::log_template::LogTemplate;
use crate::protocol::EventType;
use crate::state::app_state::AppState;
use anyhow::{Context, Result};
use serde_json::json;
use std::sync::LazyLock;

/// OAuth2 protocol action handler
pub struct OAuth2Protocol;

impl OAuth2Protocol {
    pub fn new() -> Self {
        Self
    }
}

// Implement Protocol trait (common functionality)
impl Protocol for OAuth2Protocol {
    fn get_async_actions(&self, _state: &AppState) -> Vec<ActionDefinition> {
        // OAuth2 has no async actions - it's purely request-response
        Vec::new()
    }
    fn get_sync_actions(&self) -> Vec<ActionDefinition> {
        vec![
            oauth2_authorize_response_action(),
            oauth2_token_response_action(),
            oauth2_introspect_response_action(),
            oauth2_error_response_action(),
        ]
    }
    fn protocol_name(&self) -> &'static str {
        "OAuth2"
    }
    fn get_event_types(&self) -> Vec<EventType> {
        get_oauth2_event_types()
    }
    fn stack_name(&self) -> &'static str {
        "ETH>IP>TCP>HTTP>OAuth2"
    }
    fn keywords(&self) -> Vec<&'static str> {
        vec![
            "oauth2",
            "oauth",
            "oauth 2.0",
            "via oauth2",
            "authorization server",
        ]
    }
    fn metadata(&self) -> crate::protocol::metadata::ProtocolMetadataV2 {
        use crate::protocol::metadata::{DevelopmentState, ProtocolMetadataV2};

        ProtocolMetadataV2::builder()
            .state(DevelopmentState::Experimental)
            .implementation(
                "Manual RFC 6749/7662/7009 endpoints over hyper HTTP/1.1. Simulator: tokens are \
                 opaque strings the model invents, nothing is signed, nothing is stored, and no \
                 credential is ever verified.",
            )
            .llm_control(
                "Whether to approve an authorization request, what token strings to return, and \
                 what a token introspects as. Client id/secret are handed to the model as text; \
                 the server itself checks nothing.",
            )
            .e2e_testing("reqwest HTTP client - OAuth2 flow testing")
            .notes(
                "Not an authorization server: no signing keys, no token database, no client \
                 registry, no PKCE, no TLS. Suitable for exercising OAuth2 clients and for \
                 honeypots, never for guarding anything real.",
            )
            .max_inbound_bytes(crate::server::oauth2::MAX_REQUEST_BYTES)
            .request_only("OAuth 2.0 is HTTP request/response; a server cannot send a peer anything unprompted")
            .build()
    }
    fn description(&self) -> &'static str {
        "OAuth2 authorization-server simulator (LLM decides; no tokens are signed or stored)"
    }
    fn example_prompt(&self) -> &'static str {
        "Act as an OAuth2 server on port 8080. Accept client 'testapp' with secret 'secret123'. Issue tokens with 1-hour expiry."
    }
    fn group_name(&self) -> &'static str {
        "AI & API"
    }

    fn get_startup_examples(&self) -> crate::llm::actions::StartupExamples {
        use crate::llm::actions::StartupExamples;
        use serde_json::json;

        // Deterministic: issue a fixed authorization code, echoing the client's
        // state parameter, no LLM call. This is an explicit operator decision to
        // always approve โ€” the LLM path must instead default to refusal.
        let script = r#"import json, sys
data = json.load(sys.stdin)
event = data["event"]
if data["event_type_id"] == "oauth2_authorize":
    actions = [{"type": "oauth2_authorize_response",
                "code": "AUTH_CODE_xyz123",
                "state": event.get("state", "")}]
else:
    actions = []
print(json.dumps({"actions": actions}))"#;

        StartupExamples::new(
            // LLM mode: LLM handles OAuth2 authorization
            json!({
                "type": "open_server",
                "port": 8080,
                "base_stack": "oauth2",
                "instruction": "Act as OAuth2 authorization server. Accept client 'testapp' with secret 'secret123'. Issue tokens with 1-hour expiry."
            }),
            // Script mode: Code-based OAuth2 handling
            json!({
                "type": "open_server",
                "port": 8080,
                "base_stack": "oauth2",
                "event_handlers": [{
                    "event_pattern": "oauth2_authorize",
                    "handler": {
                        "type": "script",
                        "language": "python",
                        "code": script
                    }
                }]
            }),
            // Static mode: Fixed OAuth2 responses
            json!({
                "type": "open_server",
                "port": 8080,
                "base_stack": "oauth2",
                "event_handlers": [
                    {
                        "event_pattern": "oauth2_authorize",
                        "handler": {
                            "type": "static",
                            "actions": [{
                                "type": "oauth2_authorize_response",
                                "code": "AUTH_CODE_xyz123",
                                "state": "random_state"
                            }]
                        }
                    },
                    {
                        "event_pattern": "oauth2_token",
                        "handler": {
                            "type": "static",
                            "actions": [{
                                "type": "oauth2_token_response",
                                "access_token": "ACCESS_TOKEN_xyz123",
                                "token_type": "Bearer",
                                "expires_in": 3600
                            }]
                        }
                    }
                ]
            }),
        )
    }
}

// Implement Server trait (server-specific functionality)
impl Server for OAuth2Protocol {
    fn spawn(
        &self,
        ctx: crate::protocol::SpawnContext,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = anyhow::Result<std::net::SocketAddr>> + Send>,
    > {
        Box::pin(async move {
            use crate::server::oauth2::OAuth2Server;
            OAuth2Server::spawn_with_llm_actions(
                ctx.legacy_listen_addr(),
                ctx.llm_client,
                ctx.state,
                ctx.status_tx,
                ctx.server_id,
            )
            .await
        })
    }
    fn execute_action(&self, action: serde_json::Value) -> Result<ActionResult> {
        let action_type = action
            .get("type")
            .and_then(|v| v.as_str())
            .context("Missing 'type' field in action")?;

        match action_type {
            "oauth2_authorize_response" => self.execute_oauth2_authorize_response(action),
            "oauth2_token_response" => self.execute_oauth2_token_response(action),
            "oauth2_introspect_response" => self.execute_oauth2_introspect_response(action),
            "oauth2_error_response" => self.execute_oauth2_error_response(action),
            _ => Err(anyhow::anyhow!("Unknown OAuth2 action: {action_type}")),
        }
    }
}

/// Envelope key identifying which OAuth2 action produced an [`ActionResult::Output`].
///
/// Every executor below wraps its payload as `{"oauth2_result": <kind>, ...}` so the
/// HTTP layer in `mod.rs` can tell an *approval* from a *denial*. Before this existed the
/// handlers just fished a `code` field out of whatever JSON came back, so an
/// `oauth2_error_response` โ€” the only way the model can say "no" โ€” parsed as "no code
/// present", fell through to the hardcoded default, and the client received a redirect
/// carrying a perfectly usable authorization code. A denial silently became an approval.
pub const OAUTH2_RESULT_KEY: &str = "oauth2_result";

impl OAuth2Protocol {
    /// Execute oauth2_authorize_response sync action
    fn execute_oauth2_authorize_response(&self, action: serde_json::Value) -> Result<ActionResult> {
        let code = action
            .get("code")
            .and_then(|v| v.as_str())
            .context("Missing 'code' field")?;
        let state = action.get("state").and_then(|v| v.as_str());

        let response = json!({
            OAUTH2_RESULT_KEY: "authorize",
            "code": code,
            "state": state,
        });
        let bytes = serde_json::to_vec(&response)?;
        Ok(ActionResult::Output(bytes))
    }

    /// Execute oauth2_token_response sync action
    fn execute_oauth2_token_response(&self, action: serde_json::Value) -> Result<ActionResult> {
        let access_token = action
            .get("access_token")
            .and_then(|v| v.as_str())
            .context("Missing 'access_token' field")?;
        let token_type = action
            .get("token_type")
            .and_then(|v| v.as_str())
            .unwrap_or("Bearer");
        let expires_in = action
            .get("expires_in")
            .and_then(|v| v.as_i64())
            .unwrap_or(3600);

        let mut response = json!({
            OAUTH2_RESULT_KEY: "token",
            "access_token": access_token,
            "token_type": token_type,
            "expires_in": expires_in
        });

        // Optional fields
        if let Some(refresh_token) = action.get("refresh_token").and_then(|v| v.as_str()) {
            response["refresh_token"] = json!(refresh_token);
        }
        if let Some(scope) = action.get("scope").and_then(|v| v.as_str()) {
            response["scope"] = json!(scope);
        }

        let bytes = serde_json::to_vec(&response)?;
        Ok(ActionResult::Output(bytes))
    }

    /// Execute oauth2_introspect_response sync action
    fn execute_oauth2_introspect_response(
        &self,
        action: serde_json::Value,
    ) -> Result<ActionResult> {
        let active = action
            .get("active")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let mut response = json!({
            OAUTH2_RESULT_KEY: "introspect",
            "active": active
        });

        // If active, include additional fields
        if active {
            if let Some(scope) = action.get("scope").and_then(|v| v.as_str()) {
                response["scope"] = json!(scope);
            }
            if let Some(client_id) = action.get("client_id").and_then(|v| v.as_str()) {
                response["client_id"] = json!(client_id);
            }
            if let Some(exp) = action.get("exp").and_then(|v| v.as_i64()) {
                response["exp"] = json!(exp);
            }
            if let Some(token_type) = action.get("token_type").and_then(|v| v.as_str()) {
                response["token_type"] = json!(token_type);
            }
        }

        let bytes = serde_json::to_vec(&response)?;
        Ok(ActionResult::Output(bytes))
    }

    /// Execute oauth2_error_response sync action
    fn execute_oauth2_error_response(&self, action: serde_json::Value) -> Result<ActionResult> {
        let error = action
            .get("error")
            .and_then(|v| v.as_str())
            .context("Missing 'error' field")?;

        let mut response = json!({
            OAUTH2_RESULT_KEY: "error",
            "error": error
        });

        if let Some(error_description) = action.get("error_description").and_then(|v| v.as_str()) {
            response["error_description"] = json!(error_description);
        }
        if let Some(error_uri) = action.get("error_uri").and_then(|v| v.as_str()) {
            response["error_uri"] = json!(error_uri);
        }
        // RFC 6749 ยง5.2: the token/introspection endpoints answer an error with 400, except
        // invalid_client which is 401. The model may override, but the default must never be
        // the 200 that the previous code sent for every error.
        let status = action
            .get("status_code")
            .and_then(|v| v.as_u64())
            .unwrap_or(if error == "invalid_client" { 401 } else { 400 });
        response["status_code"] = json!(status);

        let bytes = serde_json::to_vec(&response)?;
        Ok(ActionResult::Output(bytes))
    }
}

// ============================================================================
// OAuth2 Action Definitions
// ============================================================================

fn oauth2_authorize_response_action() -> ActionDefinition {
    ActionDefinition {
        name: "oauth2_authorize_response".to_string(),
        description: "Send authorization code response".to_string(),
        parameters: vec![
            Parameter {
                name: "code".to_string(),
                type_hint: "string".to_string(),
                description: "Authorization code to return".to_string(),
                required: true,
            },
            Parameter {
                name: "state".to_string(),
                type_hint: "string".to_string(),
                description: "State parameter from request".to_string(),
                required: false,
            },
        ],
        example: json!({
            "type": "oauth2_authorize_response",
            "code": "AUTH_CODE_xyz123",
            "state": "random_state"
        }),
        log_template: Some(
            LogTemplate::new()
                .with_info("-> OAuth2 authorize code issued")
                .with_debug("OAuth2 oauth2_authorize_response: code issued"),
        ),
    }
}

fn oauth2_token_response_action() -> ActionDefinition {
    ActionDefinition {
        name: "oauth2_token_response".to_string(),
        description: "Send access token response".to_string(),
        parameters: vec![
            Parameter {
                name: "access_token".to_string(),
                type_hint: "string".to_string(),
                description: "Access token to issue".to_string(),
                required: true,
            },
            Parameter {
                name: "token_type".to_string(),
                type_hint: "string".to_string(),
                description: "Token type (typically 'Bearer')".to_string(),
                required: false,
            },
            Parameter {
                name: "expires_in".to_string(),
                type_hint: "number".to_string(),
                description: "Token lifetime in seconds".to_string(),
                required: false,
            },
            Parameter {
                name: "refresh_token".to_string(),
                type_hint: "string".to_string(),
                description: "Refresh token (optional)".to_string(),
                required: false,
            },
            Parameter {
                name: "scope".to_string(),
                type_hint: "string".to_string(),
                description: "Granted scopes (space-separated)".to_string(),
                required: false,
            },
        ],
        example: json!({
            "type": "oauth2_token_response",
            "access_token": "ACCESS_xyz123",
            "token_type": "Bearer",
            "expires_in": 3600,
            "refresh_token": "REFRESH_xyz123",
            "scope": "read write"
        }),
        log_template: Some(
            LogTemplate::new()
                .with_info("-> OAuth2 token issued type={token_type} expires={expires_in}s")
                .with_debug("OAuth2 oauth2_token_response: type={token_type}, expires_in={expires_in}, scope={scope}"),
        ),
    }
}

fn oauth2_introspect_response_action() -> ActionDefinition {
    ActionDefinition {
        name: "oauth2_introspect_response".to_string(),
        description: "Send token introspection response".to_string(),
        parameters: vec![
            Parameter {
                name: "active".to_string(),
                type_hint: "boolean".to_string(),
                description: "Whether token is active".to_string(),
                required: true,
            },
            Parameter {
                name: "scope".to_string(),
                type_hint: "string".to_string(),
                description: "Token scopes".to_string(),
                required: false,
            },
            Parameter {
                name: "client_id".to_string(),
                type_hint: "string".to_string(),
                description: "Client ID".to_string(),
                required: false,
            },
            Parameter {
                name: "exp".to_string(),
                type_hint: "number".to_string(),
                description: "Expiration timestamp".to_string(),
                required: false,
            },
            Parameter {
                name: "token_type".to_string(),
                type_hint: "string".to_string(),
                description: "Token type, typically 'Bearer' (only echoed back when active=true)"
                    .to_string(),
                required: false,
            },
        ],
        example: json!({
            "type": "oauth2_introspect_response",
            "active": true,
            "scope": "read write",
            "client_id": "client123",
            "token_type": "Bearer",
            "exp": 1234567890
        }),
        log_template: Some(
            LogTemplate::new()
                .with_info("-> OAuth2 introspect active={active}")
                .with_debug("OAuth2 oauth2_introspect_response: active={active}, client_id={client_id}, scope={scope}"),
        ),
    }
}

fn oauth2_error_response_action() -> ActionDefinition {
    ActionDefinition {
        name: "oauth2_error_response".to_string(),
        description: "Send OAuth2 error response".to_string(),
        parameters: vec![
            Parameter {
                name: "error".to_string(),
                type_hint: "string".to_string(),
                description: "Error code (e.g., 'invalid_request', 'unauthorized_client')"
                    .to_string(),
                required: true,
            },
            Parameter {
                name: "error_description".to_string(),
                type_hint: "string".to_string(),
                description: "Human-readable error description".to_string(),
                required: false,
            },
            Parameter {
                name: "error_uri".to_string(),
                type_hint: "string".to_string(),
                description: "URI with error information".to_string(),
                required: false,
            },
            Parameter {
                name: "status_code".to_string(),
                type_hint: "number".to_string(),
                description: "HTTP status for the error (default: 400, or 401 for invalid_client). \
                              Ignored on /authorize, which answers errors with a redirect per RFC 6749 ยง4.1.2.1."
                    .to_string(),
                required: false,
            },
        ],
        example: json!({
            "type": "oauth2_error_response",
            "error": "invalid_client",
            "error_description": "Client authentication failed"
        }),
        log_template: Some(
            LogTemplate::new()
                .with_info("-> OAuth2 error {error}")
                .with_debug(
                    "OAuth2 oauth2_error_response: error={error}, description={error_description}",
                ),
        ),
    }
}

// ============================================================================
// OAuth2 Event Type Constants
// ============================================================================

/// OAuth2 authorize event - triggered when client requests authorization
pub static OAUTH2_AUTHORIZE_EVENT: LazyLock<EventType> = LazyLock::new(|| {
    EventType::new(
        "oauth2_authorize",
        "OAuth2 authorization request received",
        json!({
            "type": "oauth2_authorize_response",
            "code": "AUTH_CODE_xyz123",
            "state": "echo the state parameter from the request"
        }),
    )
    .with_alternative_example(json!({
        "type": "oauth2_error_response",
        "error": "unauthorized_client",
        "error_description": "Client 'evilapp' is not registered"
    }))
    .with_parameters(vec![
        Parameter {
            name: "response_type".to_string(),
            type_hint: "string".to_string(),
            description: "Response type (e.g., 'code', 'token')".to_string(),
            required: true,
        },
        Parameter {
            name: "client_id".to_string(),
            type_hint: "string".to_string(),
            description: "Client identifier".to_string(),
            required: true,
        },
        Parameter {
            name: "redirect_uri".to_string(),
            type_hint: "string".to_string(),
            description: "Redirection URI".to_string(),
            required: false,
        },
        Parameter {
            name: "scope".to_string(),
            type_hint: "string".to_string(),
            description: "Requested scopes".to_string(),
            required: false,
        },
        Parameter {
            name: "state".to_string(),
            type_hint: "string".to_string(),
            description: "State parameter for CSRF protection".to_string(),
            required: false,
        },
    ])
    // These must be the *real* definitions. `call_llm` advertises `event.event_type.actions`,
    // not `get_sync_actions()`, so the stubs that used to live here (`parameters: vec![]`,
    // `example: json!({})`) were the entire vocabulary the model got: it was told
    // `oauth2_authorize_response` existed but never told that it takes a `code`.
    .with_actions(vec![
        oauth2_authorize_response_action(),
        oauth2_error_response_action(),
    ])
    .with_log_template(
        LogTemplate::new()
            .with_info("OAuth2 authorize {response_type} from {client_id}")
            .with_debug("OAuth2 authorize {response_type} from {client_id}, scope={scope}")
            .with_trace("OAuth2 authorize: {json_pretty(.)}"),
    )
});

/// OAuth2 token event - triggered when client requests access token
pub static OAUTH2_TOKEN_EVENT: LazyLock<EventType> = LazyLock::new(|| {
    EventType::new(
        "oauth2_token",
        "OAuth2 token request received",
        json!({
            "type": "oauth2_token_response",
            "access_token": "ACCESS_xyz123",
            "token_type": "Bearer",
            "expires_in": 3600,
            "scope": "read write"
        }),
    )
    .with_alternative_example(json!({
        "type": "oauth2_error_response",
        "error": "invalid_grant",
        "error_description": "Authorization code has expired"
    }))
    .with_parameters(vec![
        Parameter {
            name: "grant_type".to_string(),
            type_hint: "string".to_string(),
            description:
                "Grant type (authorization_code, refresh_token, password, client_credentials)"
                    .to_string(),
            required: true,
        },
        Parameter {
            name: "code".to_string(),
            type_hint: "string".to_string(),
            description: "Authorization code (for authorization_code grant)".to_string(),
            required: false,
        },
        Parameter {
            name: "redirect_uri".to_string(),
            type_hint: "string".to_string(),
            description: "Redirection URI".to_string(),
            required: false,
        },
        Parameter {
            name: "client_id".to_string(),
            type_hint: "string".to_string(),
            description: "Client identifier".to_string(),
            required: false,
        },
        Parameter {
            name: "client_secret".to_string(),
            type_hint: "string".to_string(),
            description: "Client secret".to_string(),
            required: false,
        },
        Parameter {
            name: "refresh_token".to_string(),
            type_hint: "string".to_string(),
            description: "Refresh token (for refresh_token grant)".to_string(),
            required: false,
        },
        Parameter {
            name: "username".to_string(),
            type_hint: "string".to_string(),
            description: "Username (for password grant)".to_string(),
            required: false,
        },
        Parameter {
            name: "password".to_string(),
            type_hint: "string".to_string(),
            description: "Password (for password grant)".to_string(),
            required: false,
        },
        Parameter {
            name: "scope".to_string(),
            type_hint: "string".to_string(),
            description: "Requested scopes".to_string(),
            required: false,
        },
    ])
    .with_actions(vec![
        oauth2_token_response_action(),
        oauth2_error_response_action(),
    ])
    .with_log_template(
        LogTemplate::new()
            .with_info("OAuth2 token {grant_type}")
            .with_debug("OAuth2 token {grant_type}, client={client_id}")
            .with_trace("OAuth2 token: {json_pretty(.)}"),
    )
});

/// OAuth2 introspect event - triggered when token introspection is requested
pub static OAUTH2_INTROSPECT_EVENT: LazyLock<EventType> = LazyLock::new(|| {
    EventType::new(
        "oauth2_introspect",
        "OAuth2 token introspection request",
        json!({
            "type": "oauth2_introspect_response",
            "active": true,
            "scope": "read write",
            "client_id": "client123",
            "token_type": "Bearer",
            "exp": 1234567890
        }),
    )
    .with_alternative_example(json!({
        "type": "oauth2_introspect_response",
        "active": false
    }))
    .with_parameters(vec![
        Parameter {
            name: "token".to_string(),
            type_hint: "string".to_string(),
            description: "Token to introspect".to_string(),
            required: true,
        },
        Parameter {
            name: "token_type_hint".to_string(),
            type_hint: "string".to_string(),
            description: "Hint about token type (access_token, refresh_token)".to_string(),
            required: false,
        },
    ])
    .with_actions(vec![
        oauth2_introspect_response_action(),
        oauth2_error_response_action(),
    ])
    .with_log_template(
        LogTemplate::new()
            .with_info("OAuth2 introspect")
            .with_debug("OAuth2 introspect, token_type={token_type_hint}")
            .with_trace("OAuth2 introspect: {json_pretty(.)}"),
    )
});

/// OAuth2 revoke event - triggered when token revocation is requested
pub static OAUTH2_REVOKE_EVENT: LazyLock<EventType> = LazyLock::new(|| {
    EventType::new(
        "oauth2_revoke",
        "OAuth2 token revocation request. RFC 7009 ยง2.2 requires the server to answer 200 \
         whether or not the token existed, so the response body is fixed and no protocol \
         action can change it; note the revocation in memory if it matters later.",
        json!({
            "type": "append_memory",
            "value": "revoked token: ACCESS_xyz123"
        }),
    )
    // Deliberately no protocol actions, hence with_no_actions() rather than an empty list:
    // the reply is fixed by RFC 7009 and mod.rs sends it regardless of what the model says.
    // Left empty, `call_llm` would log a BUG and (in debug builds) trip a debug_assert.
    .with_no_actions()
    .with_parameters(vec![
        Parameter {
            name: "token".to_string(),
            type_hint: "string".to_string(),
            description: "Token to revoke".to_string(),
            required: true,
        },
        Parameter {
            name: "token_type_hint".to_string(),
            type_hint: "string".to_string(),
            description: "Hint about token type (access_token, refresh_token)".to_string(),
            required: false,
        },
    ])
    .with_log_template(
        LogTemplate::new()
            .with_info("OAuth2 revoke")
            .with_debug("OAuth2 revoke, token_type={token_type_hint}")
            .with_trace("OAuth2 revoke: {json_pretty(.)}"),
    )
});

/// Get OAuth2 event types
pub fn get_oauth2_event_types() -> Vec<EventType> {
    vec![
        OAUTH2_AUTHORIZE_EVENT.clone(),
        OAUTH2_TOKEN_EVENT.clone(),
        OAUTH2_INTROSPECT_EVENT.clone(),
        OAUTH2_REVOKE_EVENT.clone(),
    ]
}