dwctl 8.49.0

The Doubleword Control Layer - A self-hostable observability and analytics platform for LLM applications
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
//! HTTP handlers for webhook management endpoints.

use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::Json,
};
use sqlx_pool_router::PoolProvider;
use tracing::instrument;

use crate::{
    AppState,
    api::models::webhooks::{
        UserWebhookPathParams, WebhookCreate, WebhookPathParams, WebhookResponse, WebhookUpdate, WebhookWithSecretResponse,
    },
    auth::permissions,
    db::handlers::Webhooks,
    db::models::webhooks::{WebhookCreateDBRequest, WebhookUpdateDBRequest},
    errors::{Error, Result},
    types::{Operation, Permission, Resource, UserId, UserIdOrCurrent},
    webhooks::{WebhookEventType, WebhookScope, signing},
};

/// List all webhooks for a user.
#[utoipa::path(
    get,
    path = "/users/{user_id}/webhooks",
    tag = "webhooks",
    summary = "List webhooks",
    description = "List all webhooks for a user. Users can list their own webhooks; admins can list any user's webhooks; members of an organization can list webhooks owned by that organization (read-only).",
    params(
        ("user_id" = uuid::Uuid, Path, description = "User ID"),
    ),
    responses(
        (status = 200, description = "List of webhooks", body = [WebhookResponse]),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 500, description = "Internal server error"),
    ),
    security(
        ("BearerAuth" = []),
        ("CookieAuth" = []),
        ("X-Doubleword-User" = [])
    )
)]
#[instrument(skip_all)]
pub async fn list_webhooks<P: PoolProvider>(
    State(state): State<AppState<P>>,
    Path(params): Path<UserWebhookPathParams>,
    current_user: crate::api::models::users::CurrentUser,
) -> Result<Json<Vec<WebhookResponse>>> {
    let target_user_id: UserId = match params.user_id {
        UserIdOrCurrent::Current(_) => current_user.id,
        UserIdOrCurrent::Id(id) => id,
    };

    // Allowed if any of:
    //  - admin permission (ReadAll)
    //  - reading own webhooks (ReadOwn)
    //  - target is an organization the caller belongs to (any role) — read-only
    //    access for org members, so they can spot delivery failures and notify
    //    admins. Mutating handlers stay restricted to owner/admin via
    //    can_manage_org_resource.
    let can_read_all = permissions::has_permission(&current_user, Resource::Webhooks, Operation::ReadAll);
    let can_read_own =
        target_user_id == current_user.id && permissions::has_permission(&current_user, Resource::Webhooks, Operation::ReadOwn);

    if !can_read_all && !can_read_own {
        let mut conn = state.db.read().acquire().await.map_err(|e| Error::Database(e.into()))?;
        let is_member = permissions::is_org_member(&current_user, target_user_id, &mut conn)
            .await
            .map_err(Error::Database)?;
        if !is_member {
            return Err(Error::InsufficientPermissions {
                required: Permission::Any(vec![
                    Permission::Allow(Resource::Webhooks, Operation::ReadAll),
                    Permission::Allow(Resource::Webhooks, Operation::ReadOwn),
                ]),
                action: Operation::ReadAll,
                resource: format!("webhooks for user {}", target_user_id),
            });
        }
    }

    let mut conn = state.db.read().acquire().await.map_err(|e| Error::Database(e.into()))?;
    let mut repo = Webhooks::new(&mut conn);

    let webhooks = repo.list_by_user(target_user_id).await?;
    let responses: Vec<WebhookResponse> = webhooks.into_iter().map(Into::into).collect();

    Ok(Json(responses))
}

/// Create a new webhook for a user.
#[utoipa::path(
    post,
    path = "/users/{user_id}/webhooks",
    tag = "webhooks",
    summary = "Create webhook",
    description = "Create a new webhook for a user. Returns the secret which is only shown once.",
    params(
        ("user_id" = uuid::Uuid, Path, description = "User ID"),
    ),
    request_body = WebhookCreate,
    responses(
        (status = 201, description = "Webhook created", body = WebhookWithSecretResponse),
        (status = 400, description = "Bad request"),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 500, description = "Internal server error"),
    ),
    security(
        ("BearerAuth" = []),
        ("CookieAuth" = []),
        ("X-Doubleword-User" = [])
    )
)]
#[instrument(skip_all)]
pub async fn create_webhook<P: PoolProvider>(
    State(state): State<AppState<P>>,
    Path(params): Path<UserWebhookPathParams>,
    current_user: crate::api::models::users::CurrentUser,
    Json(request): Json<WebhookCreate>,
) -> Result<(StatusCode, Json<WebhookWithSecretResponse>)> {
    let target_user_id: UserId = match params.user_id {
        UserIdOrCurrent::Current(_) => current_user.id,
        UserIdOrCurrent::Id(id) => id,
    };

    // Check permissions: can create all webhooks OR create own webhooks
    let can_create_all = permissions::has_permission(&current_user, Resource::Webhooks, Operation::CreateAll);
    let can_create_own =
        target_user_id == current_user.id && permissions::has_permission(&current_user, Resource::Webhooks, Operation::CreateOwn);

    if !can_create_all && !can_create_own {
        let mut conn = state.db.read().acquire().await.map_err(|e| Error::Database(e.into()))?;
        let can_org = permissions::can_manage_org_resource(&current_user, target_user_id, &mut conn)
            .await
            .map_err(Error::Database)?;
        if !can_org {
            return Err(Error::InsufficientPermissions {
                required: Permission::Any(vec![
                    Permission::Allow(Resource::Webhooks, Operation::CreateAll),
                    Permission::Allow(Resource::Webhooks, Operation::CreateOwn),
                ]),
                action: Operation::CreateAll,
                resource: format!("webhooks for user {}", target_user_id),
            });
        }
    }

    // Validate URL is HTTPS (allow HTTP for localhost/127.0.0.1 in development)
    let is_local = request.url.starts_with("http://localhost") || request.url.starts_with("http://127.0.0.1");
    if !request.url.starts_with("https://") && !is_local {
        return Err(Error::BadRequest {
            message: "Webhook URL must use HTTPS (HTTP allowed for localhost only)".to_string(),
        });
    }

    // Validate scope
    if request.scope != "own" && request.scope != "platform" {
        return Err(Error::BadRequest {
            message: format!("Invalid scope: '{}'. Valid scopes are: own, platform", request.scope),
        });
    }

    // Platform scope requires PlatformManager role (fail fast before hitting DB trigger)
    if request.scope == "platform" && !current_user.roles.contains(&crate::Role::PlatformManager) {
        return Err(Error::InsufficientPermissions {
            required: Permission::Allow(Resource::Webhooks, Operation::CreateAll),
            action: Operation::CreateAll,
            resource: "platform-scoped webhooks".to_string(),
        });
    }

    // Validate event types if provided
    if let Some(ref event_types) = request.event_types {
        for event_type in event_types {
            let parsed = event_type.parse::<WebhookEventType>().map_err(|_| Error::BadRequest {
                message: format!(
                    "Invalid event type: '{}'. Valid types are: batch.completed, batch.failed, user.created, batch.created, api_key.created",
                    event_type,
                ),
            })?;
            // Validate event type matches webhook scope
            let expected_scope = if request.scope == "platform" {
                WebhookScope::Platform
            } else {
                WebhookScope::Own
            };
            if parsed.scope() != expected_scope {
                return Err(Error::BadRequest {
                    message: format!(
                        "Event type '{}' belongs to scope '{:?}', but webhook scope is '{}'",
                        event_type,
                        parsed.scope(),
                        request.scope,
                    ),
                });
            }
        }
    }

    // Generate secret
    let secret = signing::generate_secret();

    let mut tx = state.db.write().begin().await.map_err(|e| Error::Database(e.into()))?;
    let mut repo = Webhooks::new(&mut tx);

    let db_request = WebhookCreateDBRequest {
        user_id: target_user_id,
        url: request.url,
        secret,
        event_types: request.event_types,
        description: request.description,
        scope: request.scope,
    };

    let webhook = repo.create(&db_request).await?;
    tx.commit().await.map_err(|e| Error::Database(e.into()))?;

    Ok((StatusCode::CREATED, Json(webhook.into())))
}

/// Get a specific webhook.
#[utoipa::path(
    get,
    path = "/users/{user_id}/webhooks/{webhook_id}",
    tag = "webhooks",
    summary = "Get webhook",
    description = "Get a specific webhook. Users can read their own webhooks; admins can read any user's webhooks; members of an organization can read webhooks owned by that organization (read-only). Secret is not included in the response.",
    params(
        ("user_id" = uuid::Uuid, Path, description = "User ID"),
        ("webhook_id" = uuid::Uuid, Path, description = "Webhook ID"),
    ),
    responses(
        (status = 200, description = "Webhook details", body = WebhookResponse),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Webhook not found"),
        (status = 500, description = "Internal server error"),
    ),
    security(
        ("BearerAuth" = []),
        ("CookieAuth" = []),
        ("X-Doubleword-User" = [])
    )
)]
#[instrument(skip_all)]
pub async fn get_webhook<P: PoolProvider>(
    State(state): State<AppState<P>>,
    Path(params): Path<WebhookPathParams>,
    current_user: crate::api::models::users::CurrentUser,
) -> Result<Json<WebhookResponse>> {
    let target_user_id: UserId = match params.user_id {
        UserIdOrCurrent::Current(_) => current_user.id,
        UserIdOrCurrent::Id(id) => id,
    };

    // Same authorization model as list_webhooks: admin (ReadAll), owner
    // (ReadOwn), or member of the target organization (read-only).
    let can_read_all = permissions::has_permission(&current_user, Resource::Webhooks, Operation::ReadAll);
    let can_read_own =
        target_user_id == current_user.id && permissions::has_permission(&current_user, Resource::Webhooks, Operation::ReadOwn);

    if !can_read_all && !can_read_own {
        let mut conn = state.db.read().acquire().await.map_err(|e| Error::Database(e.into()))?;
        let is_member = permissions::is_org_member(&current_user, target_user_id, &mut conn)
            .await
            .map_err(Error::Database)?;
        if !is_member {
            return Err(Error::InsufficientPermissions {
                required: Permission::Any(vec![
                    Permission::Allow(Resource::Webhooks, Operation::ReadAll),
                    Permission::Allow(Resource::Webhooks, Operation::ReadOwn),
                ]),
                action: Operation::ReadAll,
                resource: format!("webhook {}", params.webhook_id),
            });
        }
    }

    let mut conn = state.db.read().acquire().await.map_err(|e| Error::Database(e.into()))?;
    let mut repo = Webhooks::new(&mut conn);

    let webhook = repo.get_by_id(params.webhook_id).await?.ok_or_else(|| Error::NotFound {
        resource: "Webhook".to_string(),
        id: params.webhook_id.to_string(),
    })?;

    // Verify the webhook belongs to the specified user
    if webhook.user_id != target_user_id {
        return Err(Error::NotFound {
            resource: "Webhook".to_string(),
            id: params.webhook_id.to_string(),
        });
    }

    Ok(Json(webhook.into()))
}

/// Update a webhook.
#[utoipa::path(
    patch,
    path = "/users/{user_id}/webhooks/{webhook_id}",
    tag = "webhooks",
    summary = "Update webhook",
    description = "Update a webhook's URL, enabled status, event types, or description.",
    params(
        ("user_id" = uuid::Uuid, Path, description = "User ID"),
        ("webhook_id" = uuid::Uuid, Path, description = "Webhook ID"),
    ),
    request_body = WebhookUpdate,
    responses(
        (status = 200, description = "Webhook updated", body = WebhookResponse),
        (status = 400, description = "Bad request"),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Webhook not found"),
        (status = 500, description = "Internal server error"),
    ),
    security(
        ("BearerAuth" = []),
        ("CookieAuth" = []),
        ("X-Doubleword-User" = [])
    )
)]
#[instrument(skip_all)]
pub async fn update_webhook<P: PoolProvider>(
    State(state): State<AppState<P>>,
    Path(params): Path<WebhookPathParams>,
    current_user: crate::api::models::users::CurrentUser,
    Json(request): Json<WebhookUpdate>,
) -> Result<Json<WebhookResponse>> {
    let target_user_id: UserId = match params.user_id {
        UserIdOrCurrent::Current(_) => current_user.id,
        UserIdOrCurrent::Id(id) => id,
    };

    // Check permissions
    let can_update_all = permissions::has_permission(&current_user, Resource::Webhooks, Operation::UpdateAll);
    let can_update_own =
        target_user_id == current_user.id && permissions::has_permission(&current_user, Resource::Webhooks, Operation::UpdateOwn);

    if !can_update_all && !can_update_own {
        let mut conn = state.db.read().acquire().await.map_err(|e| Error::Database(e.into()))?;
        let can_org = permissions::can_manage_org_resource(&current_user, target_user_id, &mut conn)
            .await
            .map_err(Error::Database)?;
        if !can_org {
            return Err(Error::InsufficientPermissions {
                required: Permission::Any(vec![
                    Permission::Allow(Resource::Webhooks, Operation::UpdateAll),
                    Permission::Allow(Resource::Webhooks, Operation::UpdateOwn),
                ]),
                action: Operation::UpdateAll,
                resource: format!("webhook {}", params.webhook_id),
            });
        }
    }

    // Validate URL if provided (same localhost exception as create)
    if let Some(ref url) = request.url {
        let is_local = url.starts_with("http://localhost") || url.starts_with("http://127.0.0.1");
        if !url.starts_with("https://") && !is_local {
            return Err(Error::BadRequest {
                message: "Webhook URL must use HTTPS (HTTP allowed for localhost only)".to_string(),
            });
        }
    }

    // Validate event types if provided
    if let Some(Some(ref event_types)) = request.event_types {
        for event_type in event_types {
            if event_type.parse::<WebhookEventType>().is_err() {
                return Err(Error::BadRequest {
                    message: format!(
                        "Invalid event type: {}. Valid types are: batch.completed, batch.failed, user.created, batch.created, api_key.created",
                        event_type
                    ),
                });
            }
        }
    }

    let mut tx = state.db.write().begin().await.map_err(|e| Error::Database(e.into()))?;
    let mut repo = Webhooks::new(&mut tx);

    // First verify the webhook exists and belongs to the user
    let existing = repo.get_by_id(params.webhook_id).await?.ok_or_else(|| Error::NotFound {
        resource: "Webhook".to_string(),
        id: params.webhook_id.to_string(),
    })?;

    if existing.user_id != target_user_id {
        return Err(Error::NotFound {
            resource: "Webhook".to_string(),
            id: params.webhook_id.to_string(),
        });
    }

    let db_request = WebhookUpdateDBRequest {
        url: request.url,
        enabled: request.enabled,
        event_types: request.event_types,
        description: request.description,
    };

    let webhook = repo.update(params.webhook_id, &db_request).await?.ok_or_else(|| Error::NotFound {
        resource: "Webhook".to_string(),
        id: params.webhook_id.to_string(),
    })?;

    tx.commit().await.map_err(|e| Error::Database(e.into()))?;

    Ok(Json(webhook.into()))
}

/// Delete a webhook.
#[utoipa::path(
    delete,
    path = "/users/{user_id}/webhooks/{webhook_id}",
    tag = "webhooks",
    summary = "Delete webhook",
    description = "Delete a webhook.",
    params(
        ("user_id" = uuid::Uuid, Path, description = "User ID"),
        ("webhook_id" = uuid::Uuid, Path, description = "Webhook ID"),
    ),
    responses(
        (status = 204, description = "Webhook deleted"),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Webhook not found"),
        (status = 500, description = "Internal server error"),
    ),
    security(
        ("BearerAuth" = []),
        ("CookieAuth" = []),
        ("X-Doubleword-User" = [])
    )
)]
#[instrument(skip_all)]
pub async fn delete_webhook<P: PoolProvider>(
    State(state): State<AppState<P>>,
    Path(params): Path<WebhookPathParams>,
    current_user: crate::api::models::users::CurrentUser,
) -> Result<StatusCode> {
    let target_user_id: UserId = match params.user_id {
        UserIdOrCurrent::Current(_) => current_user.id,
        UserIdOrCurrent::Id(id) => id,
    };

    // Check permissions
    let can_delete_all = permissions::has_permission(&current_user, Resource::Webhooks, Operation::DeleteAll);
    let can_delete_own =
        target_user_id == current_user.id && permissions::has_permission(&current_user, Resource::Webhooks, Operation::DeleteOwn);

    if !can_delete_all && !can_delete_own {
        let mut conn = state.db.read().acquire().await.map_err(|e| Error::Database(e.into()))?;
        let can_org = permissions::can_manage_org_resource(&current_user, target_user_id, &mut conn)
            .await
            .map_err(Error::Database)?;
        if !can_org {
            return Err(Error::InsufficientPermissions {
                required: Permission::Any(vec![
                    Permission::Allow(Resource::Webhooks, Operation::DeleteAll),
                    Permission::Allow(Resource::Webhooks, Operation::DeleteOwn),
                ]),
                action: Operation::DeleteAll,
                resource: format!("webhook {}", params.webhook_id),
            });
        }
    }

    let mut tx = state.db.write().begin().await.map_err(|e| Error::Database(e.into()))?;
    let mut repo = Webhooks::new(&mut tx);

    // First verify the webhook exists and belongs to the user
    let existing = repo.get_by_id(params.webhook_id).await?.ok_or_else(|| Error::NotFound {
        resource: "Webhook".to_string(),
        id: params.webhook_id.to_string(),
    })?;

    if existing.user_id != target_user_id {
        return Err(Error::NotFound {
            resource: "Webhook".to_string(),
            id: params.webhook_id.to_string(),
        });
    }

    let deleted = repo.delete(params.webhook_id).await?;
    if !deleted {
        return Err(Error::NotFound {
            resource: "Webhook".to_string(),
            id: params.webhook_id.to_string(),
        });
    }

    tx.commit().await.map_err(|e| Error::Database(e.into()))?;

    Ok(StatusCode::NO_CONTENT)
}

/// Rotate a webhook's secret.
#[utoipa::path(
    post,
    path = "/users/{user_id}/webhooks/{webhook_id}/rotate-secret",
    tag = "webhooks",
    summary = "Rotate webhook secret",
    description = "Generate a new secret for a webhook. Returns the new secret which is only shown once.",
    params(
        ("user_id" = uuid::Uuid, Path, description = "User ID"),
        ("webhook_id" = uuid::Uuid, Path, description = "Webhook ID"),
    ),
    responses(
        (status = 200, description = "Secret rotated", body = WebhookWithSecretResponse),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Webhook not found"),
        (status = 500, description = "Internal server error"),
    ),
    security(
        ("BearerAuth" = []),
        ("CookieAuth" = []),
        ("X-Doubleword-User" = [])
    )
)]
#[instrument(skip_all)]
pub async fn rotate_secret<P: PoolProvider>(
    State(state): State<AppState<P>>,
    Path(params): Path<WebhookPathParams>,
    current_user: crate::api::models::users::CurrentUser,
) -> Result<Json<WebhookWithSecretResponse>> {
    let target_user_id: UserId = match params.user_id {
        UserIdOrCurrent::Current(_) => current_user.id,
        UserIdOrCurrent::Id(id) => id,
    };

    // Check permissions (use UpdateOwn/UpdateAll for secret rotation)
    let can_update_all = permissions::has_permission(&current_user, Resource::Webhooks, Operation::UpdateAll);
    let can_update_own =
        target_user_id == current_user.id && permissions::has_permission(&current_user, Resource::Webhooks, Operation::UpdateOwn);

    if !can_update_all && !can_update_own {
        let mut conn = state.db.read().acquire().await.map_err(|e| Error::Database(e.into()))?;
        let can_org = permissions::can_manage_org_resource(&current_user, target_user_id, &mut conn)
            .await
            .map_err(Error::Database)?;
        if !can_org {
            return Err(Error::InsufficientPermissions {
                required: Permission::Any(vec![
                    Permission::Allow(Resource::Webhooks, Operation::UpdateAll),
                    Permission::Allow(Resource::Webhooks, Operation::UpdateOwn),
                ]),
                action: Operation::UpdateAll,
                resource: format!("webhook {}", params.webhook_id),
            });
        }
    }

    let mut tx = state.db.write().begin().await.map_err(|e| Error::Database(e.into()))?;
    let mut repo = Webhooks::new(&mut tx);

    // First verify the webhook exists and belongs to the user
    let existing = repo.get_by_id(params.webhook_id).await?.ok_or_else(|| Error::NotFound {
        resource: "Webhook".to_string(),
        id: params.webhook_id.to_string(),
    })?;

    if existing.user_id != target_user_id {
        return Err(Error::NotFound {
            resource: "Webhook".to_string(),
            id: params.webhook_id.to_string(),
        });
    }

    let new_secret = signing::generate_secret();
    let webhook = repo
        .rotate_secret(params.webhook_id, new_secret)
        .await?
        .ok_or_else(|| Error::NotFound {
            resource: "Webhook".to_string(),
            id: params.webhook_id.to_string(),
        })?;

    tx.commit().await.map_err(|e| Error::Database(e.into()))?;

    Ok(Json(webhook.into()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::models::users::Role;
    use crate::test::utils::*;
    use serde_json::json;
    use sqlx::PgPool;

    #[sqlx::test]
    #[test_log::test]
    async fn test_create_webhook(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let user = create_test_user(&pool, Role::StandardUser).await;

        let webhook_data = json!({
            "url": "https://example.com/webhook",
            "description": "Test webhook"
        });

        let response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks", user.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .json(&webhook_data)
            .await;

        response.assert_status(StatusCode::CREATED);
        let created: WebhookWithSecretResponse = response.json();
        assert_eq!(created.url, "https://example.com/webhook");
        assert!(created.secret.starts_with("whsec_"));
        assert!(created.enabled);
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_create_webhook_requires_https(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let user = create_test_user(&pool, Role::StandardUser).await;

        let webhook_data = json!({
            "url": "http://example.com/webhook"
        });

        let response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks", user.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .json(&webhook_data)
            .await;

        response.assert_status_bad_request();
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_create_webhook_invalid_event_type(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let user = create_test_user(&pool, Role::StandardUser).await;

        let webhook_data = json!({
            "url": "https://example.com/webhook",
            "event_types": ["invalid.event"]
        });

        let response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks", user.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .json(&webhook_data)
            .await;

        response.assert_status_bad_request();
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_list_webhooks(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let user = create_test_user(&pool, Role::StandardUser).await;

        // Create a webhook first
        let webhook_data = json!({
            "url": "https://example.com/webhook"
        });

        app.post(&format!("/admin/api/v1/users/{}/webhooks", user.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .json(&webhook_data)
            .await;

        // List webhooks
        let response = app
            .get(&format!("/admin/api/v1/users/{}/webhooks", user.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .await;

        response.assert_status_ok();
        let webhooks: Vec<WebhookResponse> = response.json();
        assert_eq!(webhooks.len(), 1);
        assert_eq!(webhooks[0].url, "https://example.com/webhook");
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_update_webhook(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let user = create_test_user(&pool, Role::StandardUser).await;

        // Create a webhook
        let webhook_data = json!({
            "url": "https://example.com/webhook"
        });

        let create_response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks", user.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .json(&webhook_data)
            .await;

        let created: WebhookWithSecretResponse = create_response.json();

        // Update the webhook
        let update_data = json!({
            "url": "https://example.com/new-webhook",
            "enabled": false
        });

        let response = app
            .patch(&format!("/admin/api/v1/users/{}/webhooks/{}", user.id, created.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .json(&update_data)
            .await;

        response.assert_status_ok();
        let updated: WebhookResponse = response.json();
        assert_eq!(updated.url, "https://example.com/new-webhook");
        assert!(!updated.enabled);
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_delete_webhook(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let user = create_test_user(&pool, Role::StandardUser).await;

        // Create a webhook
        let webhook_data = json!({
            "url": "https://example.com/webhook"
        });

        let create_response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks", user.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .json(&webhook_data)
            .await;

        let created: WebhookWithSecretResponse = create_response.json();

        // Delete the webhook
        let response = app
            .delete(&format!("/admin/api/v1/users/{}/webhooks/{}", user.id, created.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .await;

        response.assert_status(StatusCode::NO_CONTENT);

        // Verify it's deleted
        let get_response = app
            .get(&format!("/admin/api/v1/users/{}/webhooks/{}", user.id, created.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .await;

        get_response.assert_status_not_found();
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_rotate_secret(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let user = create_test_user(&pool, Role::StandardUser).await;

        // Create a webhook
        let webhook_data = json!({
            "url": "https://example.com/webhook"
        });

        let create_response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks", user.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .json(&webhook_data)
            .await;

        let created: WebhookWithSecretResponse = create_response.json();
        let old_secret = created.secret.clone();

        // Rotate the secret
        let response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks/{}/rotate-secret", user.id, created.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .await;

        response.assert_status_ok();
        let rotated: WebhookWithSecretResponse = response.json();
        assert_ne!(rotated.secret, old_secret);
        assert!(rotated.secret.starts_with("whsec_"));
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_cannot_access_other_users_webhooks(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let user1 = create_test_user(&pool, Role::StandardUser).await;
        let user2 = create_test_user(&pool, Role::StandardUser).await;

        // User1 creates a webhook
        let webhook_data = json!({
            "url": "https://example.com/webhook"
        });

        let create_response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks", user1.id))
            .add_header(&add_auth_headers(&user1)[0].0, &add_auth_headers(&user1)[0].1)
            .add_header(&add_auth_headers(&user1)[1].0, &add_auth_headers(&user1)[1].1)
            .json(&webhook_data)
            .await;

        let created: WebhookWithSecretResponse = create_response.json();

        // User2 tries to access user1's webhook
        let response = app
            .get(&format!("/admin/api/v1/users/{}/webhooks/{}", user1.id, created.id))
            .add_header(&add_auth_headers(&user2)[0].0, &add_auth_headers(&user2)[0].1)
            .add_header(&add_auth_headers(&user2)[1].0, &add_auth_headers(&user2)[1].1)
            .await;

        response.assert_status_forbidden();
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_admin_can_access_other_users_webhooks(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let user = create_test_user(&pool, Role::StandardUser).await;
        let admin = create_test_admin_user(&pool, Role::PlatformManager).await;

        // User creates a webhook
        let webhook_data = json!({
            "url": "https://example.com/webhook"
        });

        let create_response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks", user.id))
            .add_header(&add_auth_headers(&user)[0].0, &add_auth_headers(&user)[0].1)
            .add_header(&add_auth_headers(&user)[1].0, &add_auth_headers(&user)[1].1)
            .json(&webhook_data)
            .await;

        let created: WebhookWithSecretResponse = create_response.json();

        // Admin can access the webhook
        let response = app
            .get(&format!("/admin/api/v1/users/{}/webhooks/{}", user.id, created.id))
            .add_header(&add_auth_headers(&admin)[0].0, &add_auth_headers(&admin)[0].1)
            .add_header(&add_auth_headers(&admin)[1].0, &add_auth_headers(&admin)[1].1)
            .await;

        response.assert_status_ok();
    }

    // ── Read-only org member webhook access ────────────────────────────────
    //
    // Members of an org (any role, including plain "member") can list and read
    // the org's webhooks so they can spot delivery failures and notify admins,
    // but they cannot mutate them.

    /// Helper: create a webhook for an org via the API as the owner, returning
    /// the created webhook (with secret).
    async fn create_org_webhook(
        app: &axum_test::TestServer,
        owner: &crate::api::models::users::UserResponse,
        org_id: UserId,
        url: &str,
    ) -> WebhookWithSecretResponse {
        let response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks", org_id))
            .add_header(&add_auth_headers(owner)[0].0, &add_auth_headers(owner)[0].1)
            .add_header(&add_auth_headers(owner)[1].0, &add_auth_headers(owner)[1].1)
            .json(&json!({ "url": url }))
            .await;
        response.assert_status(StatusCode::CREATED);
        response.json()
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_org_member_can_list_org_webhooks_without_secrets(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let alice = create_test_user(&pool, Role::StandardUser).await;
        let bob = create_test_user(&pool, Role::StandardUser).await;
        let org = create_test_org(&pool, alice.id).await;
        add_org_member(&pool, org.id, bob.id, "member").await;

        create_org_webhook(&app, &alice, org.id, "https://example.com/hook").await;

        // Bob (plain member) lists the org's webhooks
        let response = app
            .get(&format!("/admin/api/v1/users/{}/webhooks", org.id))
            .add_header(&add_auth_headers(&bob)[0].0, &add_auth_headers(&bob)[0].1)
            .add_header(&add_auth_headers(&bob)[1].0, &add_auth_headers(&bob)[1].1)
            .await;

        response.assert_status_ok();
        let webhooks: Vec<WebhookResponse> = response.json();
        assert_eq!(webhooks.len(), 1);
        assert_eq!(webhooks[0].url, "https://example.com/hook");

        // Secrets must never appear in member-visible responses. WebhookResponse
        // has no `secret` field, but check the raw JSON too as a belt-and-braces
        // guard against future struct changes.
        let raw: serde_json::Value = response.json();
        let item = &raw.as_array().unwrap()[0];
        assert!(item.get("secret").is_none(), "list response must not include secret");
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_org_member_can_get_single_org_webhook(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let alice = create_test_user(&pool, Role::StandardUser).await;
        let bob = create_test_user(&pool, Role::StandardUser).await;
        let org = create_test_org(&pool, alice.id).await;
        add_org_member(&pool, org.id, bob.id, "member").await;

        let created = create_org_webhook(&app, &alice, org.id, "https://example.com/hook").await;

        let response = app
            .get(&format!("/admin/api/v1/users/{}/webhooks/{}", org.id, created.id))
            .add_header(&add_auth_headers(&bob)[0].0, &add_auth_headers(&bob)[0].1)
            .add_header(&add_auth_headers(&bob)[1].0, &add_auth_headers(&bob)[1].1)
            .await;

        response.assert_status_ok();
        let raw: serde_json::Value = response.json();
        assert!(raw.get("secret").is_none(), "get response must not include secret");
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_non_member_cannot_list_org_webhooks(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let alice = create_test_user(&pool, Role::StandardUser).await;
        let outsider = create_test_user(&pool, Role::StandardUser).await;
        let org = create_test_org(&pool, alice.id).await;

        create_org_webhook(&app, &alice, org.id, "https://example.com/hook").await;

        let response = app
            .get(&format!("/admin/api/v1/users/{}/webhooks", org.id))
            .add_header(&add_auth_headers(&outsider)[0].0, &add_auth_headers(&outsider)[0].1)
            .add_header(&add_auth_headers(&outsider)[1].0, &add_auth_headers(&outsider)[1].1)
            .await;

        response.assert_status_forbidden();
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_org_member_cannot_create_org_webhook(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let alice = create_test_user(&pool, Role::StandardUser).await;
        let bob = create_test_user(&pool, Role::StandardUser).await;
        let org = create_test_org(&pool, alice.id).await;
        add_org_member(&pool, org.id, bob.id, "member").await;

        let response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks", org.id))
            .add_header(&add_auth_headers(&bob)[0].0, &add_auth_headers(&bob)[0].1)
            .add_header(&add_auth_headers(&bob)[1].0, &add_auth_headers(&bob)[1].1)
            .json(&json!({ "url": "https://example.com/hook" }))
            .await;

        response.assert_status_forbidden();
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_org_member_cannot_update_org_webhook(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let alice = create_test_user(&pool, Role::StandardUser).await;
        let bob = create_test_user(&pool, Role::StandardUser).await;
        let org = create_test_org(&pool, alice.id).await;
        add_org_member(&pool, org.id, bob.id, "member").await;

        let created = create_org_webhook(&app, &alice, org.id, "https://example.com/hook").await;

        let response = app
            .patch(&format!("/admin/api/v1/users/{}/webhooks/{}", org.id, created.id))
            .add_header(&add_auth_headers(&bob)[0].0, &add_auth_headers(&bob)[0].1)
            .add_header(&add_auth_headers(&bob)[1].0, &add_auth_headers(&bob)[1].1)
            .json(&json!({ "enabled": false }))
            .await;

        response.assert_status_forbidden();
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_org_member_cannot_delete_org_webhook(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let alice = create_test_user(&pool, Role::StandardUser).await;
        let bob = create_test_user(&pool, Role::StandardUser).await;
        let org = create_test_org(&pool, alice.id).await;
        add_org_member(&pool, org.id, bob.id, "member").await;

        let created = create_org_webhook(&app, &alice, org.id, "https://example.com/hook").await;

        let response = app
            .delete(&format!("/admin/api/v1/users/{}/webhooks/{}", org.id, created.id))
            .add_header(&add_auth_headers(&bob)[0].0, &add_auth_headers(&bob)[0].1)
            .add_header(&add_auth_headers(&bob)[1].0, &add_auth_headers(&bob)[1].1)
            .await;

        response.assert_status_forbidden();
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_org_member_cannot_rotate_org_webhook_secret(pool: PgPool) {
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let alice = create_test_user(&pool, Role::StandardUser).await;
        let bob = create_test_user(&pool, Role::StandardUser).await;
        let org = create_test_org(&pool, alice.id).await;
        add_org_member(&pool, org.id, bob.id, "member").await;

        let created = create_org_webhook(&app, &alice, org.id, "https://example.com/hook").await;

        let response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks/{}/rotate-secret", org.id, created.id))
            .add_header(&add_auth_headers(&bob)[0].0, &add_auth_headers(&bob)[0].1)
            .add_header(&add_auth_headers(&bob)[1].0, &add_auth_headers(&bob)[1].1)
            .await;

        response.assert_status_forbidden();
    }

    #[sqlx::test]
    #[test_log::test]
    async fn test_org_admin_can_still_manage_webhooks(pool: PgPool) {
        // Regression guard: existing owner/admin write path must keep working
        // after we relaxed the read-permission fallback from can_manage_org_resource
        // (owner/admin only) to is_org_member (any role).
        let (app, _bg_services) = create_test_app(pool.clone(), false).await;
        let alice = create_test_user(&pool, Role::StandardUser).await;
        let bob = create_test_user(&pool, Role::StandardUser).await;
        let org = create_test_org(&pool, alice.id).await;
        add_org_member(&pool, org.id, bob.id, "admin").await;

        // Bob (org admin) creates a webhook for the org.
        let response = app
            .post(&format!("/admin/api/v1/users/{}/webhooks", org.id))
            .add_header(&add_auth_headers(&bob)[0].0, &add_auth_headers(&bob)[0].1)
            .add_header(&add_auth_headers(&bob)[1].0, &add_auth_headers(&bob)[1].1)
            .json(&json!({ "url": "https://example.com/hook" }))
            .await;

        response.assert_status(StatusCode::CREATED);
    }
}